Location>code7788 >text

The best validation component for .NET FluentValidation

Popularity:615 ℃/2024-09-03 10:46:55

preamble

NET validation framework , support for chaining operations , easy to understand , well-functioning , within the component to provide more than a dozen commonly used validators , scalability , support for custom validators , support for localized multi-language .

Projects

FluentValidation is an open source .NET library for validating properties of objects.

It provides a simple and powerful way to define and enforce validation rules, making the writing and maintenance of validation logic more intuitive and convenient.

Compared to traditional data annotations, FluentValidation provides a more flexible and extensible way of defining validation rules.

It significantly improves code readability and maintainability through a fluent and easy-to-understand syntax.

Project use

FluentValidation 11 supports the following platforms:

.NET Core 3.1、.NET 5、.NET 6、.NET 7、.NET 8、.NET Standard 2.0

1. Install FluentValidation

Installation via NuGet Package Manager or dotnet CLI.

dotnet add package FluentValidation

or NuGet Package Manager

2、

using FluentValidation;
using ;
using ;

var builder = (args);
var services = ;

//  stuff
();
();

// Add Swagger
();

// Add FV
();
();

// Add FV validators
<Program>();

// Add FV Rules to swagger
();

var app = ();

// Use Swagger
();
();

();

();

3、

public void ConfigureServices(IServiceCollection services)
{
    //  stuff
    ();
    
    // HttpContextValidatorRegistry requires access to HttpContext
    ();

    // Register FV validators
    <Startup>(lifetime: );

    // Add FV to 
    ();

    // Add swagger
    (c =>
    {
        ("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });

    // [Optional] Add INameResolver (SystemTextJsonNameResolver will be registered by default)
    // <INameResolver, CustomNameResolver>();

    // Adds FluentValidationRules staff to Swagger. (Minimal configuration)
    ();

    // [Optional] Configure generation options for your needs. Also can be done with <SchemaGenerationOptions>
    // (options =>
    // {
    //      = true;
    //      = true;
    // });

    // Adds logging
    (builder => ());
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ();

    (endpoints =>
    {
        ();
    });

    // Adds swagger
    ();

    // Adds swagger UI
    (c =>
    {
        ("/swagger/v1/", "My API V1");
    });
}

4、Version compatibility

5. Supported validators

  • INotNullValidator(NotNull)
  • INotEmptyValidator(NotEmpty)
  • ILengthValidator (for strings: Length, MinimumLength, MaximumLength, ExactLength; for arrays: MinItems, MaxItems)
  • IRegularExpressionValidator(Email、Matches)
  • IComparisonValidator(GreaterThan、GreaterThanOrEqual、LessThan、LessThanOrEqual)
  • IBetweenValidator(InclusiveBetween、ExclusiveBetween)

6、Expandable

A FluentValidationRule can be registered to a ServiceCollection.

A custom rule name will replace the default rule with the same name.

A complete list of default rules can be obtained with ().

Default rule list: Required NotEmpty Length Pattern Comparison Between

new FluentValidationRule("Pattern")
{
    Matches = propertyValidator => propertyValidator is IRegularExpressionValidator,
    Apply = context =>
    {
        var regularExpressionValidator = (IRegularExpressionValidator);
        [].Pattern = ;
    }
}

7. Swagger models and validators

public class Sample
{
    public string PropertyWithNoRules { get; set; }

    public string NotNull { get; set; }
    public string NotEmpty { get; set; }
    public string EmailAddress { get; set; }
    public string RegexField { get; set; }

    public int ValueInRange { get; set; }
    public int ValueInRangeExclusive { get; set; }

    public float ValueInRangeFloat { get; set; }
    public double ValueInRangeDouble { get; set; }
}

public class SampleValidator : AbstractValidator<Sample>
{
    public SampleValidator()
    {
        RuleFor(sample => ).NotNull();
        RuleFor(sample => ).NotEmpty();
        RuleFor(sample => ).EmailAddress();
        RuleFor(sample => ).Matches(@"(\d{4})-(\d{2})-(\d{2})");

        RuleFor(sample => ).GreaterThanOrEqualTo(5).LessThanOrEqualTo(10);
        RuleFor(sample => ).GreaterThan(5).LessThan(10);

        // WARNING: Swashbuckle implements minimum and maximim as int so you will loss fraction part of float and double numbers
        RuleFor(sample => ).InclusiveBetween(1.1f, 5.3f);
        RuleFor(sample => ).ExclusiveBetween(2.2, 7.5f);
    }
}

8. Includes validator

public class CustomerValidator : AbstractValidator<Customer>
{
    public CustomerValidator()
    {
        RuleFor(customer => ).NotEmpty();
        RuleFor(customer => ).NotEmpty().WithMessage("Please specify a first name");

        Include(new CustomerAddressValidator());
    }
}

internal class CustomerAddressValidator : AbstractValidator<Customer>
{
    public CustomerAddressValidator()
    {
        RuleFor(customer => ).Length(20, 250);
    }
}

Advanced Usage

1、Asynchronous verification

RuleForAsync(x => ).MustAsync(async (usercode, cancellation) =>
{
    var code = await _userService.IsUserNameUniqueAsync(usercode);
    return code;
}).WithMessage("User code already exists");

2. Conditional validation

When(x => , () =>
{
    RuleFor(x => ).NotEmpty().WithMessage("Administration must be a super administrator");
});

3、Customized validation rules

RuleFor(x => ).Custom((value, context) =>
{
    if (value < 10 || value > 1000)
    {
        ("The number must be between 10 and 1000.");
    }
});

4、Customize the error message

RuleFor(x => ).NotEmpty().WithMessage("User name cannot be null")
       .Matches(@"^\d{6}$").WithMessage("Please enter a valid 6-digit user name"); 

Project Address

GitHub:/FluentValidation/FluentValidation

summarize

FluentValidation is an elegant and powerful validation library that improves code readability and maintainability while maintaining a high degree of flexibility.

Whether it's a simple validation requirement or a complex business rule, FluentValidation makes it easy to ensure the validity of your data.

If people have validation requirements in their projects, they can try it to improve development efficiency.

ultimate

If you found this article helpful, why not support it with a like? Your support is what keeps me motivated to continue sharing my knowledge. Feel free to leave a comment if you have any questions or need further help.

You can also join WeChat[DotNet Technician] community to share ideas and grow with other tech-loving peers!Excellence is a habit, so feel free to leave a comment and learn!