Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 41 ยท Forms and Validation

Validation with Data Annotations

Validate Blazor forms with Data Annotations: Required, StringLength, Range, RegularExpression, EmailAddress, Compare, ErrorMessage, DataAnnotationsValidator, ValidationMessage and ValidationSummary.

Validation rules in Blazor live on the model, as attributes from System.ComponentModel.DataAnnotations. A small component, DataAnnotationsValidator, connects those attributes to the form: when a field changes or the form is submitted, it checks the rules and tells the EditContext which fields are invalid. Then ValidationMessage and ValidationSummary show the messages.

Good news for this lesson: Data Annotations are plain .NET, so the runnable examples below use the real Validator class on Piston. Only the Blazor components (the .razor code) are read-only.

Annotating a model

C#
using System.ComponentModel.DataAnnotations;

public class RegisterModel
{
    [Required(ErrorMessage = "Please enter your name.")]
    [StringLength(40, MinimumLength = 2, ErrorMessage = "Name must be 2 to 40 characters.")]
    public string Name { get; set; } = "";

    [Required, EmailAddress]
    public string Email { get; set; } = "";

    [Range(18, 120, ErrorMessage = "Age must be between {1} and {2}.")]
    public int Age { get; set; }

    [Required, MinLength(8)]
    public string Password { get; set; } = "";

    [Compare(nameof(Password), ErrorMessage = "Passwords do not match.")]
    public string ConfirmPassword { get; set; } = "";

    [RegularExpression(@"^[A-Z]{2}\d{4}$", ErrorMessage = "Use two capitals and four digits.")]
    public string? Code { get; set; }

    [Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the terms.")]
    public bool AcceptTerms { get; set; }
}

The most common attributes:

Attribute Checks
[Required] Not null and (for strings) not empty or whitespace
[StringLength(max, MinimumLength = n)] Length bounds
[MinLength], [MaxLength] Length bounds for strings and collections
[Range(min, max)] Number or date bounds
[RegularExpression(pattern)] Text matches the pattern
[EmailAddress], [Url], [Phone], [CreditCard] Format checks (simple, not a delivery guarantee)
[Compare(other)] Equal to another property

Messages can use placeholders: is the display name, , the attribute arguments. Use [Display(Name = "Date of birth")] to change what shows.

Remember the nullable trap: with nullable reference types on, a string property that is never assigned by the user is "", not null. [Required] treats "" as missing, which is what you want. For value types, int Age is 0 when untouched, so use int? plus [Required] if "not entered" must differ from zero.

Wiring it into a form

HTML
<EditForm Model="model" OnValidSubmit="Register">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <p>
        <label>Name <InputText @bind-Value="model.Name" /></label>
        <ValidationMessage For="() => model.Name" />
    </p>
    <p>
        <label>Email <InputText @bind-Value="model.Email" /></label>
        <ValidationMessage For="() => model.Email" />
    </p>
    <button>Register</button>
</EditForm>

@code {
    private RegisterModel model = new();
    private void Register() { /* only runs when everything is valid */ }
}
  • DataAnnotationsValidator must be inside the EditForm.
  • ValidationSummary lists every message at once, ValidationMessage For=... shows messages of one field. The For parameter takes a lambda so the field identity is checked at compile time.
  • Field-level validation runs when a field changes (after parsing). Model-level validation (all fields) runs on submit.

When does validation run?

sequenceDiagram
  participant U as User
  participant I as InputText
  participant C as EditContext
  participant V as DataAnnotationsValidator
  U->>I: types and leaves the field
  I->>C: NotifyFieldChanged
  C->>V: OnFieldChanged
  V->>C: validate that field, store messages
  C-->>U: ValidationMessage updates
  U->>C: presses submit
  C->>V: OnValidationRequested
  V->>C: validate whole model
  C-->>U: OnValidSubmit or OnInvalidSubmit

Field edits validate one field; submit validates everything.

Limits to know

  • The validator checks top-level properties of the model. Nested objects and collections are not validated unless you use the experimental Microsoft.AspNetCore.Components.DataAnnotations.Validation package with [ValidateComplexType] on the property and ObjectGraphDataAnnotationsValidator instead of DataAnnotationsValidator.
  • Validation in the browser is not security. Always validate again on the server where data is saved (an API, a service). The next lesson shows how to add rules of your own.
  • On .NET 10 and later there are source-generated validation features for Program.cs minimal APIs; for Blazor forms the attribute approach above is still the base.

Real Data Annotations on Piston

The Validator class below is what DataAnnotationsValidator calls underneath.

C# Real Data Annotations: validate a model

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.

Stand-in: validating one field at a time

EditForm validates a single field when it changes. Validator.TryValidateProperty does the same in plain .NET:

C# Stand-in: field-level validation with ValidationMessageStore-like storage

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.

Common mistakes

  • Forgetting DataAnnotationsValidator: all models are "valid".
  • Placing it outside the EditForm: it cannot find the EditContext.
  • Using [Required] on a non-nullable int and expecting an "empty" error.
  • Duplicating messages: ValidationSummary and ValidationMessage both showing the same text is fine, but be deliberate.
  • Trusting client-side validation for security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do Data Annotation rules normally live?

    The attributes on the model describe the rules; DataAnnotationsValidator applies them.
  2. 2. What happens if an EditForm has no validator component?

    Without DataAnnotationsValidator (or another validator) nothing records errors, so OnValidSubmit always fires.
  3. 3. Which attribute checks that ConfirmPassword equals Password?

    [Compare] compares the property with another property by name.
  4. 4. Which component lists all validation messages in one place?

    ValidationSummary shows every message; ValidationMessage shows those for a single field.
  5. 5. Is browser-side Blazor validation enough to protect your data?

    Anyone can send requests without your UI, so the saving code must validate too.

Summary

  • Put rules on the model with Data Annotations.
  • Add DataAnnotationsValidator inside the EditForm, plus ValidationMessage and ValidationSummary.
  • Fields validate when edited, the whole model validates on submit.
  • Only top-level properties are checked by default; always validate on the server too.

Next: Custom Validation and Validation UI