Blazor WASM Forms Validation

Blazor WASM Forms Validation

blazor

20 Articles

Improve

In this article, let's learn about how to validate the data collected using forms in Blazor WASM application.

Note: If you have not done so already, I recommend you read the article on Blazor Wasm Forms.

Table of Contents

  1. Why Validation?
  2. Introducing DataAnnotationsValidator
  3. Displaying Error Messages
  4. Fluent Validations
  5. Summary

Why Validation?

Validation is the act of checking the validity of data. It is a very important part of the form validation process. We should always validate the user data before submitting it to the server. Validation can be from simple data format validation to complex business validations. Simple data format validations like checking email format can be done in client side while checking email uniquness in system can be done in server side. Processing the raw data can sometime allow an attacker to exploit our systems. Hence it is always recommended to validate the data before processing.

Introducing DataAnnotationsValidator

The DataAnnotationsValidator is the standard validator type in Blazor. Adding this component within an EditForm component will enable form validation based on .NET Data Annotation attributes

Code Sample - Data Annotations Validation Demo

Demo - Data Annotations Validation Demo

To demonstrate how an EditForm component works with Data Annotations validation

  1. Consider the above ExampleModel type.
  2. Several of Blazor's built-in form components.
  3. The Name property is marked required with the RequiredAttribute and specifies a StringLengthAttribute maximum string length limit and error message.
  4. The HandleValidSubmit method is assigned to OnValidSubmit. The handler is called if the form passes validation.
  5. The data annotations validator (DataAnnotationsValidator component) attaches validation support using data annotations:
    1. If the <input> form field is left blank when the Submit button is selected, an error appears in the validation summary (ValidationSummary component) ("The Name field is required.") and HandleValidSubmit is not called.
    2. If the <input> form field more than ten characters when the Submit button is selected, an error appears in the validation summary (ValidationSummary component) ("Name is too long.") and HandleValidSubmit is not called.
    3. If the <input> form field contains a valid value when the Submit button is selected, HandleValidSubmit is called.

Displaying Error Messages

Validation error messages can be displayed to the user in two ways. We can add a ValidationSummary to show a comprehensive list of all errors in the form. We can also use the ValidationMessage component to display error messages for a specific input on the form. These components are not mutually exclusive, so it is possible to use both at the same time. The ValidationSummary component can simply be dropped into an EditForm in our mark-up; no additional parameters are required at all.

As the ValidationMessage component displays error messages for a single field, it requires us to specify the identity of the field.

In the above demo when you submit the form with invalid value, you can see two error messages getting displayed. The error message above text box is from ValidationSummary and the error message below the text box is from ValidationMessage.

Fluent Validations

FluentValidation is a popular validation library for .NET by Jeremy Skinner. It has some advantages over .NET's built-in DataAnnotations validation system, such as a richer set of rules, easier configuration, and easier extensibility.

FluentValidation does not provide integration with Blazor out of the box. Let's learn how to make Fluent Validation integrate and work nicely with Blazor. Lets start by using the same ExampleModel and configure and validate using Fluent Validation using below steps.

  1. Install Nuget Package - FluentValidation
  2. Add the below FluentValidator<TValidator> to your project. This code snippet updated version of Fluent Validatoe originally created by Steve Sanderson. I have added original source link in the snippet.
  3. Now Create a YourModelClassValidator : AbstractValidator<YourModelClass>
  4. Finally add <FluentValidator TValidator="YourModelClassValidator" />

Code Sample - Fluent Validator

Code Sample - Fluent Validator Demo

Demo - Fluent Validation Demo

To demonstrate how an EditForm component works with Fluent Validation

  1. Consider the above FluentExampleModel type.
  2. Several of Blazor's built-in form components.
  3. A FluentExampleModelValidator is created and that has necessary rules defined. The Name property is chained with the NotEmpty() rule and error message and again chained with MaximumLength(10) maximum string length limit and error message.
  4. The HandleValidSubmit method is assigned to OnValidSubmit. The handler is called if the form passes validation.
  5. The data annotations validator (FluentValidator component) attaches validation support using fluent validation rules:
    1. If the <input> form field is left blank when the Submit button is selected, an error appears in the validation summary (ValidationSummary component) ("The Name field is required.") and HandleValidSubmit is not called.
    2. If the <input> form field more than ten characters when the Submit button is selected, an error appears in the validation summary (ValidationSummary component) ("Name is too long.") and HandleValidSubmit is not called.
    3. If the <input> form field contains a valid value when the Submit button is selected, HandleValidSubmit is called.

Note that I use the above method in my production apps and it works well as of now. But there are several third party libraries you can use to do this as mentioned in Fluent Validation official site:

Summary

In this article, we learn't how to validate data collected using Forms in blazor application using various techniques like DataAnnotationsValidator using .NET's built in Data Annotation Validation Attrinutes and FluentValidator using FluentValidation Library and how to display the error messages and feedback to user. DataAnnotations Validator is suffice for simple scenarios but for complex scenarios, I'd recommend FluentValidator.

  • Blazor
  • Forms
  • Validation
  • Fluent Validation