Blazor DataGrid Example - Custom Validation
This sample shows how to use data annotation to perform custom validation in the DataGrid.
Order ID | Customer ID | Employee ID | Freight | Ship City |
---|
10241 | VINET | 1 | $30.99 | Reims |
10242 | TOMSP | 2 | $50.52 | Munster |
10243 | HANAR | 3 | $32.28 | Rio de Janeir |
10244 | VICTE | 4 | $22.90 | Lyon |
10245 | VINET | 5 | $30.99 | Reims |
10246 | TOMSP | 6 | $50.52 | Munster |
10247 | HANAR | 7 | $32.28 | Rio de Janeir |
10248 | VICTE | 8 | $22.90 | Lyon |
10249 | VINET | 9 | $30.99 | Reims |
10250 | TOMSP | 10 | $50.52 | Munster |
10251 | HANAR | 11 | $32.28 | Rio de Janeir |
10252 | VICTE | 12 | $22.90 | Lyon |
The Blazor DataGrid Custom validation is used to validate the fields according to the user's condition using data annotation. System.ComponentModel.DataAnnotations namespace must be imported to use the custom validation. The user should create a new class for the field to be customized which must extend the ValidationAttribute. The IsValid method should be overridden to validate the end-user input.
In this demo, the following changes are made in the Grid
- The namespace System.ComponentModel.DataAnnotations is imported to use the custom validation.
- Created a class CustomValidationFreight for the Freight property to be validated which extends ValidationAttribute that validates whether the entered Freight value is in between 1 and 1000.
- Created a class CustomValidationEmployeeID for the EmployeeID property to be validated which extends ValidationAttribute that validates whether the entered EmployeeID value is greater than 0.
- IsValid method is overidden and accessed the input entered by the end-user.
- Validated the input entered by the end-user.
- An error message is shown if the validation is wrong.
- Created a class CustomValidationFreight for the Freight property to be validated which extends ValidationAttribute that validates whether the entered Freight value is in between 1 and 1000.
- Created a class CustomValidationEmployeeID for the EmployeeID property to be validated which extends ValidationAttribute that validates whether the entered EmployeeID value is greater than 0.
Try adding a new record in this grid with empty values to see the validations done in the columns.
More information about the Row hover can be found in this documentation section.