Asp net core web api how to validate mobile line using fluent validation

Introduction

ASP.NET is a popular programming language used for web . In this article, we will explore how to validate a mobile phone number using Fluent Validation in ASP.NET Core Web API.

What is Fluent Validation?

Fluent Validation is a .NET library that provides a fluent interface for validating . It allows you to define validation rules in a clear and concise manner, making it easier to maintain and understand your validation logic.

Setting up the ASP.NET Core Web API project

Before we dive into validating a mobile phone number, let's first set up a basic ASP.NET Core Web API project. Here's a sample code snippet to get :


using Microsoft..Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MyWebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Validating a mobile phone number

Now that we have our ASP.NET Core Web API project set up, let's proceed with validating a mobile phone number using Fluent Validation. Here's an example:

In the above code snippet, we define a validator class called MobileNumberValidator that inherits from . The MobileNumber class represents the model for our mobile number.

Inside the MobileNumberValidator class, we define a validation rule for the Number property. We use the RuleFor method to specify the property to validate and chain validation rules using fluent syntax.

In this example, we ensure that the mobile number is not empty and the regular expression pattern ^[0-9]{10}$. If the validation fails, we provide custom error messages using the WithMessage method.

Using the validator in the ASP.NET Core Web API controller

Now that we have our validator set up, let's use it in our ASP.NET Core Web API controller. Here's an example:


using Microsoft.AspNetCore.Mvc;

namespace MyWebApi.
{
    [ApiController]
    [Route("api/[controller]")]
    public class MobileNumberController : ControllerBase
    {
        [HttpPost]
        public IActionResult ValidateMobileNumber([FromBody] MobileNumber mobileNumber)
        {
            var validator = new MobileNumberValidator();
            var validationResult = validator.Validate(mobileNumber);

            if (!validationResult.IsValid)
            {
                return BadRequest(validationResult.Errors);
            }

            return Ok("Mobile number is valid.");
        }
    }
}

In the above code snippet, we define a controller called MobileNumberController with a POST action method ValidateMobileNumber. The action method a MobileNumber as input, which will be validated using the MobileNumberValidator.

We create an instance of the MobileNumberValidator and call the Validate method to perform the validation. If the validation fails, we return a BadRequest response with the validation errors. Otherwise, we return an Ok response indicating that the mobile number is valid.

Conclusion

In this article, we have explored how to validate a mobile phone number using Fluent Validation in ASP.NET Core Web API. Fluent Validation provides a convenient and expressive way to define validation rules for your models. By following the examples provided, you can easily incorporate Fluent Validation into your ASP.NET Core Web API projects.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents