The most popular .NET library for creating strongly typed validation rules for your models is Fluent Validation. It allows you to define rules for classes and properties of your classes in a simple and flexible way (using readable, fluent yet expressive syntax).
With Fluent Validation you don't need to write manual validation logic in your model classes; instead you can put your validation rules in a separate class which separates concerns and makes the code clean and maintainable.
Step 1 :Install FluentValidation
Step 2 : Create a Model Class
public class RegisterModel
{
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
Step 3 : Create a Validator Class
using FluentValidation;
public class RegisterModelValidator : AbstractValidator<RegisterModel>
{
public RegisterModelValidator()
{
RuleFor(x => x.Username)
.NotEmpty().WithMessage("Username is required.")
.Length(3, 20).WithMessage("Username must be between 3 and 20 characters.");
RuleFor(x => x.Password)
.NotEmpty().WithMessage("Password is required.")
.MinimumLength(6).WithMessage("Password must be at least 6 characters long.");
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required.")
.EmailAddress().WithMessage("Invalid email address.");
}
}
Step 4 : Register FluentValidation in Startup
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
}
}
Fluent Validation offers you a structured, maintainable way of validation in your .NET application.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our .Net Expertise.
0