.NET

FluentValidation NuGet Package


Introduction

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.

 

Advantages of FluentValidation

  1. Separation of Concerns: The models become a little bit cleaner and more business oriented by separating it from the actual validation logic.
  2. Fluent API: The fluent syntax provides for readable, easy to understand validation rules.
  3. Built-in Validators: Built in Fluent Validation are tons of built in validation methods (for example: validate email, length etc.).
  4. Custom Validators: When the built in validators don't have what you need, you can easily create your own custom validation logic.
  5. Integration with ASP.NET Core: Running seamlessly on top of the ASP.NET Core, it is a part of your controller action and can be used for model validation.
  6. Supports Complex Validations: Fluent Validation also supports complex validation cases including the ability to have conditional validations and cross property validations.

Example

Step 1 :Install FluentValidation

  1. Install NuGet Package 
  2. dotnet add package FluentValidation.AspNetCore

 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

.Net

Related Center Of Excellence