FluentValidation là thư viện validation mạnh mẽ cho .NET, dùng fluent interface và lambda expression.
Cài đặt
dotnet add package FluentValidation
Validators cho string length
| Method | Mô tả |
|---|---|
MaximumLength(int) | Độ dài tối đa (≤ max) |
MinimumLength(int) | Độ dài tối thiểu (≥ min) |
Length(int min, int max) | Khoảng [min, max] |
ExactLength(int) | Độ dài chính xác |
Ví dụ hoàn chỉnh
using FluentValidation;
using FluentValidation.Results;
using System;
using System.Collections.Generic;
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(p => p.FirstName)
.NotEmpty().WithMessage("{PropertyName} is required")
.MaximumLength(50).WithMessage("{PropertyName} must not exceed {MaxLength} characters")
.MinimumLength(2).WithMessage("{PropertyName} must be at least {MinLength} characters");
RuleFor(p => p.LastName)
.NotEmpty().WithMessage("{PropertyName} is required")
.Length(2, 30).WithMessage("{PropertyName} must be between {MinLength} and {MaxLength} characters");
}
}
class Program
{
static void Main()
{
var person = new Person { FirstName = "A", LastName = "B" }; // Invalid: too short
var validator = new PersonValidator();
ValidationResult result = validator.Validate(person);
if (!result.IsValid)
{
foreach (var failure in result.Errors)
Console.WriteLine($"[{failure.PropertyName}] {failure.ErrorMessage}");
}
else
{
Console.WriteLine("Valid!");
}
Console.ReadLine();
}
}
Kết quả
[FirstName] FirstName must be at least 2 characters
[LastName] LastName must be between 2 and 30 characters
Placeholder trong message
{PropertyName}: Tên property (FirstName, LastName){PropertyValue}: Giá trị hiện tại{MinLength},{MaxLength},{TotalLength}: Tham số length
Cascade Mode (Ngắt chuỗi validation)
RuleFor(p => p.FirstName)
.Cascade(CascadeMode.StopOnFirstFailure) // Dừng ở lỗi đầu tiên
.NotEmpty()
.MaximumLength(50);
Async Validation (ví dụ: check unique email)
RuleFor(p => p.Email)
.NotEmpty()
.EmailAddress()
.MustAsync(async (email, ct) => await _userService.IsEmailUniqueAsync(email))
.WithMessage("Email already exists");
Lưu ý: FluentValidation chỉ validate string length cho property kiểu string. Với collection, dùng Must(x => x.Count >= min).