Blazor's built-in client-side validation lets developers enforce data integrity and guarantee user input follows specified rules and limits.
Validation in Blazor is typically implemented using data annotations, which allow developers to decorate model properties with validation attributes such as Required, StringLength, or Range.
When working with forms, Blazor's EditForm component automatically handles client-side validation based on these data annotations, displaying error messages and preventing form submission until all validation rules are satisfied.
[Required(ErrorMessage = "The Name field is required.")]
[StringLength(50, ErrorMessage = "Name cannot be longer than 50 characters.")]
public string Name { get; set; }
[Range(1, 100, ErrorMessage = "Age must be between 1 and 100.")]
public int Age { get; set; }
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
Common data annotation attributes include:
- [Required]
- [StringLength(maxLength, MinimumLength = 0)]
- [Range(minimum, maximum)]
- [EmailAddress]
- [Phone]
- [Compare(otherProperty, ErrorMessage = "Passwords do not match.")]
- [RegularExpression(pattern, ErrorMessage = "Invalid format.")]
- [DataType(DataType.*)] (While primarily for UI hints, some can influence validation)
Use EditForm, DataAnnotationsValidator, and ValidationSummary
<div class="form-group">
<label for="name">Name:</label>
<InputText id="name" @bind-Value="model.Name" class="form-control" />
<ValidationMessage For="@(() => model.Name)" class="text-danger" />
</div>
Blazor's built-in validation capabilities, developers can easily apply custom validation logic.
Implementing IValidatableObject in your model: This interface allows you to define custom validation rules at the model level. The Validate method returns a collection of ValidationResult objects indicating any errors.
using System.ComponentModel.DataAnnotations;
public class CustomModel : IValidatableObject
{
[Required]
public string Field1 { get; set; }public string Field2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!string.IsNullOrEmpty(Field1) && !string.IsNullOrEmpty(Field2) && Field1 == Field2)
{
yield return new ValidationResult(
"Field1 and Field2 cannot have the same value.",
new[] { "Field1", "Field2" });
}
}
}