Overview

Clean.Net uses FluentValidation for request validation. The validation pipeline is automatically configured and will execute for any endpoint that has a validator defined for the corresponding request model.

Validation occurs before the request reaches your handler, ensuring invalid requests are rejected early in the pipeline.
Implementing Validation

To add validation for an endpoint:

1. Request Model
// Define the request model
public class CreateUserRequest : IRequest<Result<CreateUserResponse>>
{
    public string Username { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}
2. Create Validator
// Create a validator, implement the validation rules and bind it to the corresponding request model
public class CreateUserValidator : AbstractValidator<CreateUserRequest>
{
    public CreateUserValidator()
    {
        RuleFor(x => x.Username)
            .NotEmpty()
            .MinimumLength(3)
            .MaximumLength(50);

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

        RuleFor(x => x.Password)
            .NotEmpty()
            .MinimumLength(8)
            .Matches("[A-Z]").WithMessage("Password must contain uppercase letter")
            .Matches("[0-9]").WithMessage("Password must contain number");
    }
}
Validation Response

Clean.Net follows the RFC 7807 Problem Details standard for validation error responses. This provides clear, structured JSON error messages with details like type, title, status, and an errors list for specific issues. When validation fails, the API automatically returns a 400 Bad Request with validation details.

{
    "type": "ValidationError",
    "title": "One or more validation errors occurred",
    "status": 400,
    "errors": {
        {
            "code": "UsernameNotProvided",
            "message": "Please provide a Username",
            "fieldName": "Username"
        },
        {
        "code": "PasswordNotProvided",
        "message": "Please provide a Password",
        "fieldName": "Password"
        }
    }
}
Pro Tip: Validators are automatically discovered and registered by the dependency injection container. Just create your validator class and validation will be executed automatically.