Popular Posts

May 12, 2024

ASP.NET Core Data Validations with FluentValidation

FluentValidation is a .NET library used for validation in applications developed using the .NET framework. It provides a fluent interface for defining validation rules for your classes. With FluentValidation, you can define validation rules in a clear and expressive way, making your code more readable and maintainable.

Instead of cluttering your domain classes with validation logic, you can create separate validator classes that define the validation rules for each class. This separation of concerns helps keep your codebase clean and organized.

FluentValidation supports various types of validation rules, including basic checks like required fields, string length, and numeric range, as well as more complex validations such as custom validation logic and cross-property validations.

Overall, FluentValidation simplifies the process of validating input data in .NET applications and promotes clean, maintainable code by separating validation concerns from domain logic.



Create a project named FluentValidationTest.

Run this commands to install fluent validation :

-          Install-Package FluentValidation

-          Install-Package FluentValidation.AspNetCore

-          Install-Package FluentValidation.DependencyInjectionExtensions

 

In Program.cs file add this lines:

builder.Services.AddFluentValidation(v =>

{

    v.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());

});

 

 

In Models Folder create a class named it “CustomerModel”

public class CustomerModel

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }

    public decimal Height { get; set; }

    public int Age { get; set; }

    public string Phone { get; set; }

 

 

    public AddressModel PrimaryAddress { get; set; }

    public List<AddressModel> OtherAddresses { get; set; }

 

}

 

Create a directory named Validators

Create a class named CustomerValidator.cs

    public class CustomerValidator : AbstractValidator<CustomerModel>

    {

        public CustomerValidator()

        {

            //RuleFor(x => x.FirstName).NotNull().NotEmpty();

            //RuleFor(x => x.LastName).NotNull().NotEmpty();

 

            

 

            RuleFor(x => x.FirstName).NotEmpty().WithMessage("First Name is required.");

            RuleFor(x => x.LastName).NotEmpty().WithMessage("Last Name is required.");

            RuleFor(x => x.Email).NotNull().NotEmpty().EmailAddress();

            RuleFor(x => x.Height).ScalePrecision(1, 3);

            RuleFor(x => x.Age).InclusiveBetween(18, 50);

 

            RuleFor(x => x.Phone).Must(phone =>

                !string.IsNullOrEmpty(phone) && phone.StartsWith("+")

            ).WithMessage("Phone must starts with + sign.");

 

 

            RuleFor(x => x.PrimaryAddress).InjectValidator();

//  You can also specify any child validators for complex properties

//  by using the SetValidator method.

            RuleFor(x => x.PrimaryAddress).SetValidator(new AddressValidator());

//  To validator the OtherAddresses collection, you can use the RuleForEach 

//  method to associate the same validator to multiple items in a collection.

            RuleForEach(x => x.OtherAddresses).SetValidator(new AddressValidator());

        }

 

 

}

 

 

Create a controller CustomerController

Add this controller:

public IActionResult Create()

{

    return View();

}

 

 

[HttpPost]

public IActionResult Create(CustomerModel model)

{

    if (!ModelState.IsValid)

    {

        return View(model);

    }

 

    //TODO: Save the customer to the database.

 

    return Ok();

}

 

 

Create view:

@model FluentValidationTest.Models.CustomerModel

 

@{

    ViewData["Title"] = "Create";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

 

 

<h3>Add Customer</h3>

<hr />

 

<form asp-action="Create" method="post">

    <div class="row">

        <div class="col-md-6">

            <div class="form-group">

                <label>First Name</label>

                <input asp-for="FirstName" class="form-control" />

                <span asp-validation-for="FirstName" class="text-danger"></span>

            </div>

        </div>

        <div class="col-md-6">

            <div class="form-group">

                <label>Last Name</label>

                <input asp-for="LastName" class="form-control" />

                <span asp-validation-for="LastName" class="text-danger"></span>

            </div>

        </div>

    </div>

    <div class="row">

        <div class="col-md-6">

            <div class="form-group">

                <label>Email</label>

                <input asp-for="Email" class="form-control" />

                <span asp-validation-for="Email" class="text-danger"></span>

            </div>

        </div>

        <div class="col-md-6">

            <div class="form-group">

                <label>Height</label>

                <input asp-for="Height" class="form-control" />

                <span asp-validation-for="Height" class="text-danger"></span>

            </div>

        </div>

    </div>

    <div class="row">

        <div class="col-md-6">

            <div class="form-group">

                <label>Age</label>

                <input asp-for="Age" class="form-control" />

                <span asp-validation-for="Age" class="text-danger"></span>

            </div>

        </div>

        <div class="col-md-6">

            <div class="form-group">

                <label>Phone</label>

                <input asp-for="Phone" class="form-control" />

                <span asp-validation-for="Phone" class="text-danger"></span>

            </div>

        </div>

    </div>

    <div class="row">

        <div class="col-md-6">

            <div class="form-group">

                <input type="submit" value="Create" class="btn btn-primary" />

            </div>

        </div>

    </div>

</form>



For details please visit:  https://docs.fluentvalidation.net/en/latest/inheritance.html

Github: https://github.com/itsjubayer/ASP.NET-FluentValidation-.git

 

No comments:

Post a Comment