Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 41 ยท Forms and Validation

Custom Validation and Validation UI

Write custom validation for Blazor forms: custom ValidationAttribute classes, IValidatableObject for cross-field rules, ValidationMessageStore for server errors, and styling validation messages.

Data Annotations cover the common rules, but real forms need more: "end date must be after start date", "username is already taken", "at least one topic must be ticked". Blazor gives you three levels of customisation: a custom attribute, a model-level IValidatableObject and a ValidationMessageStore that lets your own code push messages into the form.

The validation classes are plain .NET, so the first two examples run for real on Piston. The ValidationMessageStore part is Blazor-specific, so you get read-only code plus a labelled stand-in.

A custom ValidationAttribute

Inherit from ValidationAttribute and override IsValid:

C#
using System.ComponentModel.DataAnnotations;

public class NotInPastAttribute : ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext context)
    {
        if (value is DateOnly date && date < DateOnly.FromDateTime(DateTime.Today))
        {
            return new ValidationResult(
                ErrorMessage ?? $"{context.DisplayName} cannot be in the past.",
                new[] { context.MemberName! });
        }
        return ValidationResult.Success;
    }
}

public class Booking
{
    [NotInPast]
    public DateOnly Date { get; set; }
}

Return ValidationResult.Success when the value is fine. Passing the member name ties the message to that field, so ValidationMessage For=... finds it. Attributes can also take arguments through their constructor ([ForbiddenWords("admin", "root")]) so one rule serves many properties.

Convention: treat null or empty as valid in custom attributes and let [Required] handle "missing". Rules stay small and composable.

C# Real custom ValidationAttribute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Cross-field rules with IValidatableObject

Some rules involve several properties. Let the model validate itself:

C#
public class Trip : IValidatableObject
{
    [Required] public string Destination { get; set; } = "";
    public DateOnly Start { get; set; }
    public DateOnly End { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext context)
    {
        if (End < Start)
            yield return new ValidationResult("End must be on or after Start.",
                new[] { nameof(End) });
    }
}

Validate is called after the attribute checks pass, and only when validateAllProperties is on (that is the submit-time pass in EditForm). It is not called when a single field changes, so a cross-field message appears on submit rather than while the user types.

C# Real IValidatableObject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Note the third case: the attribute error is reported and Validate is not run, because Validator stops at the first stage that fails.

Server errors with ValidationMessageStore

Some checks cannot live on the model: "this username is taken" needs a database. Create a ValidationMessageStore from the EditContext, add messages and call NotifyValidationStateChanged:

HTML
<EditForm EditContext="editContext" OnValidSubmit="Register">
    <DataAnnotationsValidator />
    <InputText @bind-Value="model.Username" />
    <ValidationMessage For="() => model.Username" />
    <button>Register</button>
</EditForm>

@code {
    private RegisterModel model = new();
    private EditContext editContext = default!;
    private ValidationMessageStore messages = default!;

    protected override void OnInitialized()
    {
        editContext = new EditContext(model);
        messages = new ValidationMessageStore(editContext);
        editContext.OnValidationRequested += (_, _) => messages.Clear();
        editContext.OnFieldChanged += (_, e) => messages.Clear(e.FieldIdentifier);
    }

    private async Task Register()
    {
        if (await Users.ExistsAsync(model.Username))
        {
            messages.Add(editContext.Field(nameof(model.Username)), "That username is taken.");
            editContext.NotifyValidationStateChanged();
            return;
        }
        await Users.CreateAsync(model);
    }
}

Two habits matter: clear old messages when the user edits the field or validation restarts, and call NotifyValidationStateChanged so the components redraw.

Stand-in: a message store

C# Stand-in: ValidationMessageStore

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Styling messages and fields

ValidationMessage renders a <div class="validation-message"> per message, and ValidationSummary renders a <ul class="validation-errors"> with <li class="validation-message"> items. Style them in app.css. Both accept extra attributes, so you can add your own class:

HTML
<ValidationMessage For="() => model.Email" class="text-danger small" />

Accessibility tips: connect messages to inputs with aria-describedby and give the summary role="alert" so assistive technology announces it.

HTML
<InputText @bind-Value="model.Email" aria-describedby="email-error" />
<div id="email-error" role="alert"><ValidationMessage For="() => model.Email" /></div>

For a custom look of the whole message list, write your own component that reads EditContext.GetValidationMessages() (cascading parameter EditContext) instead of using ValidationSummary.

Common mistakes

  • Forgetting to clear the message store: errors stay forever.
  • Forgetting NotifyValidationStateChanged: messages are added but not shown.
  • Putting database checks in an attribute: attributes should be cheap and synchronous, and Data Annotations has no async hook.
  • Expecting IValidatableObject to run on each keystroke.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method do you override when writing a custom validation attribute?

    ValidationAttribute.IsValid receives the value and a ValidationContext and returns a ValidationResult.
  2. 2. When is IValidatableObject.Validate called by EditForm?

    It is part of whole-object validation, not single-field validation.
  3. 3. You add a message to a ValidationMessageStore but nothing appears. What is the likely fix?

    The store changes silently; NotifyValidationStateChanged tells validation components to redraw.
  4. 4. Why should a custom attribute usually return Success for null or empty values?

    Separating 'present' from 'well-formed' lets optional fields use your rule without becoming required.

Summary

  • Custom attributes (ValidationAttribute.IsValid) make reusable field rules.
  • IValidatableObject handles cross-field rules at submit time.
  • ValidationMessageStore pushes server-side errors into the form: clear it on edits and notify after changes.
  • Style .validation-message and add ARIA hooks for accessibility.

Next: File Uploads and InputFile