# Form Validation

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: User Interaction
Source: https://www.devtutorials.ai/learn/blazor/user-interaction/form-validation

> Form validation in Blazor: DataAnnotationsValidator, validation attributes and custom error messages, ValidationSummary and ValidationMessage, styling messages, OnValidSubmit and OnInvalidSubmit, custom attributes, cross-field rules and clearing messages.

## Validation Overview

- **Validation** means checking what the user typed **before** you accept it.
- For example: the name must not be empty, and the cups must be between 1 and 10.
- Blazor checks the rules when the form is submitted. If a value breaks a rule, Blazor shows a message next to it.
- The form is only accepted when every value is correct.

**Real-World Example:**

- Ravi's online orders sometimes have no name, or 500 cups by mistake.
- He adds rules to the order form: a name is required, and cups must be 1 to 10.
- Now a wrong order shows a red message, and only correct orders reach the kitchen.

<figure className="blz-fig">
<svg viewBox="0 0 640 200" role="img" aria-labelledby="fig-fv-flow">
  <title id="fig-fv-flow">Animation: an order with an empty name goes into a Check rules box. It comes out on the red path with the message Please enter your name. Then a correct order goes in and comes out on the green path: Order placed.</title>
  <defs><marker id="fig-fv-flow-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="20" y="75" width="140" height="50" rx="10" />
  <text className="t m" x="90" y="105" textAnchor="middle" style={{ fontSize: 12 }}>Submit order</text>
  <rect className="org" x="240" y="75" width="140" height="50" rx="10" />
  <text className="t m" x="310" y="105" textAnchor="middle" style={{ fontSize: 12 }}>Check rules</text>
  <rect x="460" y="20" width="160" height="50" rx="10" style={{ fill: "#fee2e2", stroke: "#dc2626" }} />
  <text className="t" x="540" y="42" textAnchor="middle" style={{ fontSize: 12, fill: "#b91c1c" }}>✗ Please enter</text>
  <text className="t" x="540" y="58" textAnchor="middle" style={{ fontSize: 12, fill: "#b91c1c" }}>your name</text>
  <rect className="grn" x="460" y="130" width="160" height="50" rx="10" />
  <text className="t m" x="540" y="160" textAnchor="middle" style={{ fontSize: 12 }}>✓ Order placed</text>
  <path className="line" d="M160 100 H236" markerEnd="url(#fig-fv-flow-a)" />
  <path className="line" d="M380 90 L456 50" markerEnd="url(#fig-fv-flow-a)" />
  <path className="line" d="M380 110 L456 150" markerEnd="url(#fig-fv-flow-a)" />
  <circle r="7" style={{ fill: "#dc2626" }}>
    <animate attributeName="cx" values="90;310;540;540;540" keyTimes="0;0.2;0.4;0.5;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="100;100;45;45;45" keyTimes="0;0.2;0.4;0.5;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="opacity" values="1;1;1;0;0" keyTimes="0;0.2;0.4;0.5;1" dur="6s" repeatCount="indefinite" />
  </circle>
  <circle r="7" style={{ fill: "#16a34a" }} opacity="0">
    <animate attributeName="cx" values="90;90;310;540" keyTimes="0;0.5;0.7;0.9" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="100;100;100;155" keyTimes="0;0.5;0.7;0.9" dur="6s" repeatCount="indefinite" />
    <animate attributeName="opacity" values="0;1;1;1" keyTimes="0;0.5;0.7;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Blazor checks the rules on submit. A wrong value shows a message. A correct order goes through.</figcaption>
</figure>

## Data Annotations Validation

- **Data annotations** are small tags in square brackets above a property in the model, like `[Required]`.
- Each tag is one rule. `[Required]` means "this value must not be empty".
- They live in the namespace `System.ComponentModel.DataAnnotations`, so the model file needs `using System.ComponentModel.DataAnnotations;`.

### DataAnnotationsValidator

- `<DataAnnotationsValidator />` goes inside the `EditForm`. It reads the tags in the model and checks them.
- Without it, the tags do nothing.
- `<ValidationSummary />` shows the error messages as a list. You learn it in detail below.

In the below example, `TeaOrder.cs` marks `Name` with `[Required]`. Click **Place order** with the name box empty, and a message appears.

      <p>Name: <InputText @bind-Value="order.Name" /></p>
      <button type="submit">Place order</button>

@code {
      private TeaOrder order = new();
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [Required]
      public string Name { get; set; } = "";
}
`,
  }}
/>

- The message says "The Name field is required." Type a name and click again. The message goes away.

### Validation Attributes

These are the rules you will use most:

<div className="tscroll">

| Attribute | Rule | Example |
|---|---|---|
| `[Required]` | Must not be empty | A name |
| `[StringLength(20)]` | At most 20 letters | A short note |
| `[Range(1, 10)]` | A number from 1 to 10 | Cups |
| `[EmailAddress]` | Must look like an email | ravi@teashop.com |
| `[Phone]` | Must look like a phone number | 98400 12345 |
| `[RegularExpression("...")]` | Must match a pattern | A 6-digit PIN code |

</div>

In the below example, the model uses `[Required]`, `[StringLength]`, `[Range]` and `[EmailAddress]`. Click **Place order** to see every broken rule.

      <p>Name: <InputText @bind-Value="order.Name" /></p>
      <p>Cups: <InputNumber @bind-Value="order.Cups" /></p>
      <p>Email: <InputText @bind-Value="order.Email" /></p>
      <button type="submit">Place order</button>

@code {
      private TeaOrder order = new() { Name = "A very long customer name", Cups = 0, Email = "asha" };
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [Required]
      [StringLength(10)]
      public string Name { get; set; } = "";

      [Range(1, 10)]
      public int Cups { get; set; }

      [EmailAddress]
      public string Email { get; set; } = "";
}
`,
  }}
/>

- A property can have more than one rule, like `Name` with `[Required]` and `[StringLength(10)]`.

`[Required]` does not catch `0` in an `int`, because `0` is a value. Use `[Range(1, 10)]` for numbers.

### Custom Error Messages

- The default messages, like "The field Cups must be between 1 and 10.", are not always friendly.
- Every attribute takes `ErrorMessage = "..."` to set your own text.

In the below example, each rule in `TeaOrder.cs` has its own `ErrorMessage`.

      <p>Name: <InputText @bind-Value="order.Name" /></p>
      <p>Cups: <InputNumber @bind-Value="order.Cups" /></p>
      <button type="submit">Place order</button>

@code {
      private TeaOrder order = new();
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [Required(ErrorMessage = "Please enter your name.")]
      public string Name { get; set; } = "";

      [Range(1, 10, ErrorMessage = "Order 1 to 10 cups.")]
      public int Cups { get; set; }
}
`,
  }}
/>

## Displaying Validation Errors

### ValidationSummary

- `<ValidationSummary />` shows **all** error messages of the form in one list.
- Put it at the top of the form, so the user sees everything that is wrong.

### ValidationMessage

- `<ValidationMessage For="() => order.Name" />` shows the message of **one** property.
- Put it right after the input, so the message sits next to the box it belongs to.
- `For` takes a small lambda, `() => order.Name`, that points to the property.

<figure className="blz-fig">
<svg viewBox="0 0 640 220" role="img" aria-labelledby="fig-fv-where">
  <title id="fig-fv-where">A form with a ValidationSummary box at the top listing two errors. Below it, the Name box has a ValidationMessage under it, and the Cups box has its own ValidationMessage under it.</title>
  <defs><marker id="fig-fv-where-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="140" y="10" width="360" height="200" rx="10" />
  <rect x="160" y="24" width="320" height="50" rx="6" style={{ fill: "#fee2e2", stroke: "#dc2626" }} />
  <text className="t" x="172" y="44" style={{ fontSize: 11, fill: "#b91c1c" }}>• Please enter your name.</text>
  <text className="t" x="172" y="62" style={{ fontSize: 11, fill: "#b91c1c" }}>• Order 1 to 10 cups.</text>
  <text className="t m" x="490" y="54" style={{ fontSize: 11 }}>← ValidationSummary</text>
  <rect x="160" y="88" width="200" height="26" rx="5" style={{ fill: "var(--surface, #fff)", stroke: "#dc2626" }} />
  <text className="t" x="168" y="106" style={{ fontSize: 11 }}>Name</text>
  <text className="t" x="160" y="130" style={{ fontSize: 11, fill: "#b91c1c" }}>Please enter your name.</text>
  <rect x="160" y="146" width="200" height="26" rx="5" style={{ fill: "var(--surface, #fff)", stroke: "#dc2626" }} />
  <text className="t" x="168" y="164" style={{ fontSize: 11 }}>Cups: 0</text>
  <text className="t" x="160" y="188" style={{ fontSize: 11, fill: "#b91c1c" }}>Order 1 to 10 cups.</text>
  <text className="t m" x="370" y="134" style={{ fontSize: 11 }}>← ValidationMessage</text>
  <text className="t m" x="370" y="192" style={{ fontSize: 11 }}>← ValidationMessage</text>
  <text className="t" x="20" y="54" style={{ fontSize: 11 }}>All errors, at the top</text>
  <text className="t" x="20" y="140" style={{ fontSize: 11 }}>One error, next to</text>
  <text className="t" x="20" y="156" style={{ fontSize: 11 }}>its own box</text>
</svg>
<figcaption>ValidationSummary lists every error. ValidationMessage shows one error next to its box.</figcaption>
</figure>

In the below example, the form has a `ValidationSummary` at the top and a `ValidationMessage` under each box. Click **Place order** to see both.

      <p>Name: <InputText @bind-Value="order.Name" /></p>
      <ValidationMessage For="() => order.Name" />

      <p>Cups: <InputNumber @bind-Value="order.Cups" /></p>
      <ValidationMessage For="() => order.Cups" />

      <p><button type="submit">Place order</button></p>

@code {
      private TeaOrder order = new();
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [Required(ErrorMessage = "Please enter your name.")]
      public string Name { get; set; } = "";

      [Range(1, 10, ErrorMessage = "Order 1 to 10 cups.")]
      public int Cups { get; set; }
}
`,
  }}
/>

### Styling Validation Messages

Blazor adds CSS classes, so you can style the form with CSS:

- `.validation-message`: the text of a `ValidationMessage`.
- `.validation-errors`: the list of a `ValidationSummary`.
- `.invalid`: an input with a broken rule. `.valid`: a correct input.
- `.modified`: an input the user has changed.

In the below example, the `<style>` block makes wrong boxes red, correct boxes green, and the messages small and red.

      .invalid { border: 2px solid #dc2626; }
      .valid.modified { border: 2px solid #16a34a; }
      .validation-message { color: #dc2626; font-size: 0.85em; }
</style>

      <p>Name: <InputText @bind-Value="order.Name" /></p>
      <ValidationMessage For="() => order.Name" />

      <p><button type="submit">Place order</button></p>

@code {
      private TeaOrder order = new();
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [Required(ErrorMessage = "Please enter your name.")]
      public string Name { get; set; } = "";
}
`,
  }}
/>

- Click **Place order**: the box turns red. Type a name and press **Tab**: the box turns green.

The project template's `wwwroot/app.css` already styles `.invalid`, `.valid.modified` and `.validation-message`. Change them there to match your app.

## Validation-Aware Submission

- In **Forms & Events**, you used `OnSubmit`. It runs on **every** submit, even when values are wrong.
- With validation, use `OnValidSubmit` and `OnInvalidSubmit` instead. Blazor runs the rules first and then calls the right one.

<figure className="blz-fig">
<svg viewBox="0 0 640 200" role="img" aria-labelledby="fig-fv-submit">
  <title id="fig-fv-submit">Animation: Submit goes to Rules OK? A dot goes down the Yes path to OnValidSubmit, then the No path to OnInvalidSubmit.</title>
  <defs><marker id="fig-fv-submit-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="20" y="80" width="120" height="44" rx="10" />
  <text className="t m" x="80" y="107" textAnchor="middle" style={{ fontSize: 12 }}>Submit</text>
  <rect className="org" x="210" y="80" width="130" height="44" rx="10" />
  <text className="t m" x="275" y="107" textAnchor="middle" style={{ fontSize: 12 }}>Rules OK?</text>
  <rect className="grn" x="430" y="20" width="190" height="44" rx="10" />
  <text className="t m" x="525" y="47" textAnchor="middle" style={{ fontSize: 12 }}>OnValidSubmit</text>
  <rect x="430" y="140" width="190" height="44" rx="10" style={{ fill: "#fee2e2", stroke: "#dc2626" }} />
  <text className="t m" x="525" y="167" textAnchor="middle" style={{ fontSize: 12 }}>OnInvalidSubmit</text>
  <path className="line" d="M140 102 H206" markerEnd="url(#fig-fv-submit-a)" />
  <path className="line" d="M340 95 L426 45" markerEnd="url(#fig-fv-submit-a)" />
  <path className="line" d="M340 110 L426 160" markerEnd="url(#fig-fv-submit-a)" />
  <text className="t" x="375" y="58" style={{ fontSize: 11 }}>yes</text>
  <text className="t" x="375" y="158" style={{ fontSize: 11 }}>no</text>
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="80;275;525;525;80;275;525;525" keyTimes="0;0.15;0.35;0.5;0.5;0.65;0.85;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="102;102;42;42;102;102;162;162" keyTimes="0;0.15;0.35;0.5;0.5;0.65;0.85;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Blazor checks the rules, then calls OnValidSubmit or OnInvalidSubmit.</figcaption>
</figure>

### OnValidSubmit

- `OnValidSubmit` runs **only** when every rule passes. This is where you save the order.

### OnInvalidSubmit

- `OnInvalidSubmit` runs when at least one rule fails. Use it to show a short note, like "Please fix the errors."

In the below example, `OnValidSubmit` runs `Save` and `OnInvalidSubmit` runs `ShowProblem`. Try the form empty, then with a name and 2 cups.

      <p>Name: <InputText @bind-Value="order.Name" /></p>
      <p>Cups: <InputNumber @bind-Value="order.Cups" /></p>
      <button type="submit">Place order</button>

<p>@message</p>

@code {
      private TeaOrder order = new();
      private string message = "";

      private void Save() => message = $"Order saved: {order.Cups} cups for {order.Name}.";

      private void ShowProblem() => message = "Please fix the errors above.";
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [Required(ErrorMessage = "Please enter your name.")]
      public string Name { get; set; } = "";

      [Range(1, 10, ErrorMessage = "Order 1 to 10 cups.")]
      public int Cups { get; set; }
}
`,
  }}
/>

Do not use `OnSubmit` together with `OnValidSubmit` or `OnInvalidSubmit` on the same form. Blazor stops with an error.

## Custom Validation

### Custom Validation Attributes

- When no built-in attribute fits, you can write your own.
- Make a class that ends with `Attribute` and inherits `ValidationAttribute`. Then override `IsValid`.
- `IsValid` gets the value and returns `true` (correct) or `false` (wrong).

In the below example, `OnMenuAttribute.cs` allows only teas on Ravi's menu. `TeaOrder.cs` uses it as `[OnMenu]`. Try **Coffee**, then **Ginger Tea**.

      <p>Tea: <InputText @bind-Value="order.Tea" /></p>
      <ValidationMessage For="() => order.Tea" />

      <p><button type="submit">Place order</button></p>

@code {
      private TeaOrder order = new() { Tea = "Coffee" };
}
`,
    "Models/OnMenuAttribute.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class OnMenuAttribute : ValidationAttribute
{
      private static readonly string[] Menu = { "Masala Tea", "Ginger Tea", "Lemon Tea" };

      public override bool IsValid(object? value)
      {
          return value is string tea && Menu.Contains(tea);
      }
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [OnMenu(ErrorMessage = "Sorry, that is not on our menu.")]
      public string Tea { get; set; } = "";
}
`,
  }}
/>

- You write `[OnMenu]`, not `[OnMenuAttribute]`. C# lets you leave out the word `Attribute`.

### Cross-Field Validation

- Some rules need **two** values. For example: "Home delivery needs an address".
- The model can implement `IValidatableObject`. Its `Validate` method can look at every property.
- It returns a `ValidationResult` for each problem, with the message and the property it belongs to.
- For two values that must match, like an email and "confirm email", the built-in `[Compare("Email")]` is enough.

In the below example, `Validate` in `TeaOrder.cs` returns an error when `HomeDelivery` is ticked and `Address` is empty.

      <label><InputCheckbox @bind-Value="order.HomeDelivery" /> Home delivery</label>
      <p>Address: <InputText @bind-Value="order.Address" /></p>
      <ValidationMessage For="() => order.Address" />

      <p><button type="submit">Place order</button></p>

@code {
      private TeaOrder order = new() { HomeDelivery = true };
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder : IValidatableObject
{
      public bool HomeDelivery { get; set; }
      public string Address { get; set; } = "";

      public IEnumerable<ValidationResult> Validate(ValidationContext context)
      {
          if (HomeDelivery && Address == "")
          {
              yield return new ValidationResult(
                  "Home delivery needs an address.", new[] { nameof(Address) });
          }
      }
}
`,
  }}
/>

- Untick **Home delivery** and click again. The message goes away, because pickup needs no address.

## Clearing Validation Messages

- After a good order, or when the user clicks **Clear**, the old messages should go away.
- Give the form a **new, empty model**: `order = new();`. `EditForm` then starts fresh, with no messages.
- Use `type="button"` on the **Clear** button, so it does not submit the form.

In the below example, click **Place order** with the form empty to see the messages. Then click **Clear**: the boxes and the messages are cleared.

      <p>Name: <InputText @bind-Value="order.Name" /></p>
      <button type="submit">Place order</button>
      <button type="button" @onclick="Clear">Clear</button>

<p>@message</p>

@code {
      private TeaOrder order = new();
      private string message = "";

      private void Save()
      {
          message = $"Order saved for {order.Name}.";
          Clear();
      }

      private void Clear() => order = new();
}
`,
    "Models/TeaOrder.cs": `using System.ComponentModel.DataAnnotations;

namespace BlazorApp.Models;

public class TeaOrder
{
      [Required(ErrorMessage = "Please enter your name.")]
      public string Name { get; set; } = "";
}
`,
  }}
/>

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| No `<DataAnnotationsValidator />` in the form | The attributes check by themselves | Add `<DataAnnotationsValidator />` inside the `EditForm` | No messages, and wrong orders pass |
| `OnSubmit` to save a validated form | `OnSubmit` runs only when values are correct | Use `OnValidSubmit` | Wrong orders are saved |
| `OnSubmit` and `OnValidSubmit` on one form | Both can run | Use one or the other | Blazor stops with an error |
| `[Required]` on an `int` for cups | It catches 0 | Use `[Range(1, 10)]` | 0 cups is accepted |
| `For="order.Name"` on `ValidationMessage` | `For` takes the property | Write `For="() => order.Name"` | A build error |
| No `using System.ComponentModel.DataAnnotations;` | The attributes are always known | Add the `using` line to the model file | A build error: `Required` not found |

</div>

## Check Yourself

## Exercises

## What to Remember

- Validation checks the values before you accept them.
- Put rules on the model with attributes like `[Required]`, `[Range]`, `[StringLength]` and `[EmailAddress]`. Set your own text with `ErrorMessage`.
- `<DataAnnotationsValidator />` inside the `EditForm` checks the rules.
- `ValidationSummary` lists all errors. `ValidationMessage For="() => ..."` shows one error next to its box.
- Style `.invalid`, `.valid`, `.modified` and `.validation-message` with CSS.
- Save in `OnValidSubmit`. Use `OnInvalidSubmit` for a "please fix" note.
- Write your own rule with a `ValidationAttribute`. Check two values with `IValidatableObject`.
- Clear the form and its messages with `order = new();`.

Next: **Server Rendering**
