Form Validation in Blazor
By Syncfusion®, Inc. · Last updated
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.
What you will learn
- Add rules to a model with data annotation attributes
- Show errors with ValidationSummary and ValidationMessage
- Save only correct forms with OnValidSubmit
- Write a custom validation attribute and a cross-field rule
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.
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.
Submit order
Check rules
✗ Please enter your name
✓ Order placed
Blazor checks the rules on submit. A wrong value shows a message. A correct order goes through.
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 needsusing System.ComponentModel.DataAnnotations;.
DataAnnotationsValidator
<DataAnnotationsValidator />goes inside theEditForm. 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.
- 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:
| 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 |
In the below example, the model uses [Required], [StringLength], [Range] and [EmailAddress]. Click Place order to see every broken rule.
- A property can have more than one rule, like
Namewith[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.
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.
Fortakes a small lambda,() => order.Name, that points to the property.
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.
• Please enter your name. • Order 1 to 10 cups. ← ValidationSummary
Name Please enter your name.
Cups: 0 Order 1 to 10 cups. ← ValidationMessage ← ValidationMessage All errors, at the top One error, next to its own box
ValidationSummary lists every error. ValidationMessage shows one error next to its box.
In the below example, the form has a ValidationSummary at the top and a ValidationMessage under each box. Click Place order to see both.
Styling Validation Messages
Blazor adds CSS classes, so you can style the form with CSS:
.validation-message: the text of aValidationMessage..validation-errors: the list of aValidationSummary..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.
- 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
OnValidSubmitandOnInvalidSubmitinstead. Blazor runs the rules first and then calls the right one.
Animation: Submit goes to Rules OK? A dot goes down the Yes path to OnValidSubmit, then the No path to OnInvalidSubmit.
Submit
Rules OK?
OnValidSubmit
OnInvalidSubmit
yes no
Blazor checks the rules, then calls OnValidSubmit or OnInvalidSubmit.
OnValidSubmit
OnValidSubmitruns only when every rule passes. This is where you save the order.
OnInvalidSubmit
OnInvalidSubmitruns 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.
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
Attributeand inheritsValidationAttribute. Then overrideIsValid. IsValidgets the value and returnstrue(correct) orfalse(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.
- You write
[OnMenu], not[OnMenuAttribute]. C# lets you leave out the wordAttribute.
Cross-Field Validation
- Some rules need two values. For example: "Home delivery needs an address".
- The model can implement
IValidatableObject. ItsValidatemethod can look at every property. - It returns a
ValidationResultfor 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.
- 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();.EditFormthen 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.
Common mistakes
| 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 |
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 withErrorMessage. <DataAnnotationsValidator />inside theEditFormchecks the rules.ValidationSummarylists all errors.ValidationMessage For="() => ..."shows one error next to its box.- Style
.invalid,.valid,.modifiedand.validation-messagewith CSS. - Save in
OnValidSubmit. UseOnInvalidSubmitfor a "please fix" note. - Write your own rule with a
ValidationAttribute. Check two values withIValidatableObject. - Clear the form and its messages with
order = new();.
Next: Server Rendering