Skip to content

Validation ​

Complete Example: Request, Form, and Assertions ​

The complete blog supplies PostRequest, its action, and the Blade form that displays errors and old input. Its HTTP test proves invalid JSON is rejected before a row is saved.

For validation outside HTTP, create this self-contained command:

csharp
// app/Commands/ValidationDemo.cs
using DotBlaze;
using FluentValidation;

namespace Blog.Commands;

public record SubscriberInput(string Email);

public class ValidationDemo : Command
{
    public override string Signature => "demo:validation";
    public override async Task<int> Handle()
    {
        var rules = Validator.Make<SubscriberInput>(rule =>
            rule.Field(input => input.Email).NotEmpty().EmailAddress());
        var valid = await rules.ValidateAsync(new SubscriberInput("ada@example.test"));
        var invalid = await rules.ValidateAsync(new SubscriberInput("not-an-email"));
        if (!valid.IsValid || invalid.IsValid)
            throw new InvalidOperationException("Unexpected validation result.");
        Line("Valid address accepted; invalid address rejected.");
        return 0;
    }
}

Run dotblaze demo:validation. This returns validation results; it does not produce redirects or 422 responses by itself. Those HTTP behaviors belong to the form-request filter.

Introduction ​

DotBlaze validates incoming data with form requests, like Laravel's FormRequest. The rules themselves are written with FluentValidation, so instead of strings such as 'required|email' you write r.Field(x => x.Email).NotEmpty().EmailAddress() and the compiler checks the property names.

For small forms, you can also validate inline in the controller with RuleSet<T>, without a form request class.

Standalone Validation ​

Use Validator in a service, job, command, or controller:

csharp
using FluentValidation;

var result = await Validator.Validate(input, rules =>
{
    rules.Field(x => x.Email).NotEmpty().EmailAddress();
});
if (!result.IsValid)
    foreach (var error in result.Errors)
        Log.Warning("{Field}: {Message}", error.PropertyName, error.ErrorMessage);

Validator.Make<T>(configure) returns a reusable RuleSet<T>. Validator.ValidateOrThrow(input, configure) throws FluentValidation's ValidationException when validation fails. Both validation methods await async rules and accept a cancellation token. They return validation results or throw; automatic HTTP redirects and 422 responses remain the responsibility of FormRequest<T>.

Validation Quickstart ​

This walk-through follows the post form of the sample blog.

Defining the Routes ​

csharp
Route.Middleware("auth").Group(() =>
{
    Route.Resource<PostController>("/posts", parameter: "post");
});

Writing the Form Request ​

csharp
using FluentValidation;

namespace SampleApp.Requests;

public class PostRequest : FormRequest<PostRequest>
{
    public string Title { get; set; } = "";
    public string Body { get; set; } = "";

    public override void Rules(RuleSet<PostRequest> r)
    {
        r.Field(x => x.Title).NotEmpty().MaximumLength(255);
        r.Field(x => x.Body).NotEmpty();
    }
}

Writing the Controller ​

Take the form request as an action parameter. DotBlaze validates it before the action runs, so inside the action the data is valid:

csharp
public async Task<IActionResult> Store(PostRequest request)
{
    var post = new Post { UserId = (long)Auth.Id()! };
    await post.Update(new { request.Title, request.Body });
    return RedirectRoute("posts.show", new { post = post.Id }).With("status", "Post created.");
}

When validation fails, the action is not called. Instead:

  • A normal browser request is redirected back to the previous page (the Referer, or /) with the errors and the old input flashed.
  • A request that wants JSON gets a 422 Unprocessable Entity response (see format).

Displaying the Validation Errors ​

Views read the flashed errors with helpers from DotBlazePage:

html
<input type="text" name="Title" value="@Old("Title", Model.Title)" />
@if (Error("Title") is string error)
{
    <span class="text-sm text-red-600">@error</span>
}
HelperReturns
Error(field)The first message for the field, or null.
Errors(field)All messages for the field (an empty list when there are none).
HasErrors()true when any error was flashed.
html
@if (HasErrors())
{
    <div class="text-red-600">Please fix the errors below.</div>
}

@foreach (var message in Errors("Password"))
{
    <p>@message</p>
}

Errors are keyed by property name. Lookups ignore case and underscores, so Error("title") and Error("Title") are the same.

Repopulating Forms ​

Old(field, fallback) returns the value the user submitted, or the fallback when there is none:

html
<textarea name="Body">@(Old("Body") ?? Model.Body)</textarea>

Like Laravel, DotBlaze never flashes passwords: any field whose name contains password (for example Password and PasswordConfirmation), the CSRF token, and _method are left out of the old input.

Errors and old input are flash data: they are removed at the end of the request that reads them. See how long flash data lives.

Form Request Validation ​

Creating Form Requests ​

A form request is a class that derives from FormRequest<TSelf>, passing its own type, and implements Rules. It is filled from the form fields and query string, or from the body of a JSON request (Content-Type: application/json, property names in any casing), so the same request class serves forms and API clients. The sample app keeps them in app/Http/Requests:

csharp
public class RegisterRequest : FormRequest<RegisterRequest>
{
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
    public string Password { get; set; } = "";
    public string PasswordConfirmation { get; set; } = "";

    public override void Rules(RuleSet<RegisterRequest> r)
    {
        r.Field(x => x.Name).NotEmpty().MaximumLength(255);
        r.Field(x => x.Email).NotEmpty().EmailAddress().MaximumLength(255)
            .MustAsync(async (email, _) => !await User.Where(u => u.Email == email).Exists())
            .WithMessage("This email is already registered.");
        r.Field(x => x.Password).NotEmpty().MinimumLength(8);
        r.Field(x => x.PasswordConfirmation).Equal(x => x.Password).WithMessage("The passwords do not match.");
    }
}

RuleSet<T> is a FluentValidation AbstractValidator<T>; Field(...) is its RuleFor(...). Add using FluentValidation; to get the rule methods. Asynchronous rules such as MustAsync are supported, which is how the example checks for a duplicate email in the database.

The properties are filled by MVC model binding from the form, query string, and route values. Form field names must match the property names (case-insensitive): name the confirmation field PasswordConfirmation, not password_confirmation.

Authorizing Form Requests ​

Override Authorize() to decide whether the current user may make the request at all. Returning false stops the request with an empty 403 Forbidden response before validation runs:

csharp
public override bool Authorize() => Auth.Check();

Authorize() is synchronous and has no access to route models; for ownership checks against a bound model, check in the action as the sample's PostController does.

Customizing the Error Messages ​

Use FluentValidation's WithMessage and WithName:

csharp
r.Field(x => x.Title).NotEmpty().WithMessage("Every post needs a title.");
r.Field(x => x.Body).NotEmpty().WithName("Content");   // "'Content' must not be empty."

Validation Error Response Format ​

For JSON requests, a failed validation returns 422 with the first message and every message per property:

json
{
  "message": "'Email' is not a valid email address.",
  "errors": {
    "Email": ["'Email' is not a valid email address."],
    "Password": ["'Password' must not be empty."]
  }
}

Property names in errors are kept as declared (PascalCase).

Inline Validation ​

RuleSet<T> can validate an ordinary input object; it does not need to inherit from FormRequest<T>. For example:

csharp
public class PostInput
{
    public string Title { get; set; } = "";
    public string Body { get; set; } = "";
}

In a controller deriving from BaseController, add using FluentValidation; and using Microsoft.AspNetCore.Mvc;, then define and run the rules inside the action. This example uses the authenticated route from the quickstart:

csharp
public async Task<IActionResult> Store([FromForm] PostInput input)
{
    var rules = new RuleSet<PostInput>();
    rules.Field(x => x.Title).NotEmpty().MaximumLength(255);
    rules.Field(x => x.Body).NotEmpty();

    var result = await rules.ValidateAsync(input);
    if (!result.IsValid)
    {
        var errors = result.Errors.GroupBy(e => e.PropertyName)
            .ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray());

        if (Request.WantsJson())
            return UnprocessableEntity(new { message = errors.First().Value[0], errors });

        return Back().WithErrors(errors).WithInput();
    }

    var post = new Post { UserId = (long)Auth.Id()! };
    await post.Update(new { input.Title, input.Body });
    return RedirectRoute("posts.show", new { post = post.Id }).With("status", "Post created.");
}

Inline validation does not automatically stop the action or produce an error response: check IsValid and return before saving. The example returns the same 422 error format for requests that want JSON, or redirects back with errors and old input for the existing Error(...) and Old(...) view helpers. ValidateAsync also supports asynchronous rules such as MustAsync.

This action binds form fields with [FromForm]. For a JSON-only action, use [FromBody] PostInput input and have clients send Accept: application/json for JSON errors. Ordinary input objects use MVC model binding; the automatic form-or-JSON binding described above is provided by FormRequest<T>.

Manually Adding Errors ​

Some checks only make sense in the action, such as a failed login. Redirect back with WithErrors and WithInput, and the view helpers show them like any other validation error:

csharp
public async Task<IActionResult> Login(LoginRequest request)
{
    if (await Auth.Attempt(new { request.Email, request.Password }, request.Remember))
        return Intended("/posts");

    return Back().WithErrors(new { Email = "These credentials do not match our records." }).WithInput();
}

Available Validation Rules ​

Every FluentValidation validator is available, for example:

LaravelDotBlaze (FluentValidation)
required.NotEmpty()
email.EmailAddress()
min:8 (string).MinimumLength(8)
max:255 (string).MaximumLength(255)
between:1,10.InclusiveBetween(1, 10)
in:draft,published.Must(v => new[] { "draft", "published" }.Contains(v))
regex:/^\d+$/.Matches(@"^\d+$")
same:password.Equal(x => x.Password)
unique:users,email.MustAsync(async (email, _) => !await User.Where(u => u.Email == email).Exists())

Refer to the FluentValidation documentation for the full list, conditions (When), and custom validators.

Localization ​

FluentValidation's built-in messages follow the current culture: app.locale in config/App.cs by default, or what Lang.SetLocale chose for the request:

csharp
public override object Values() => new
{
    name = "DotBlazeApp",
    locale = "id",
};

Messages set with WithMessage are used as written; translate them with __, see Localization.