Blazor custom form validation
In this video we will discuss how to create a custom validation attribute and perform custom form validation in Blazor.
Built-in attributes for validation in Blazor
For most use cases asp.net core has several built-in attributes for model validation. Some of the common built-in attributes are listed below.
Custom validation attribute example
If we have a validation requirement that cannot be implemented using the built-in attributes, we can create a custom validation attribute.
On the following Edit Employee
page, the only allowed email domain is pragimtech.com
. If any other domain name is used, we want to display a validation error. We could achieve this using the built-in regular expression validator
, but let's create a custom validator.
Create custom validation attribute
To create a custom validation attribute
- Create a class that derives from the built-in abstract
ValidationAttribute
class and overrideIsValid()
method. IsValid()
method returnsnull
if there are no validation errors, otherwise aValidationResult
object.ValidationResult
accepts 2 parameters - Validation error message and the property name with which this validation error message must be associated with.- The public property (
AllowedDomain
) allows to pass the domain name instead of hard-coding it in thisEmailDomainValidator
class. This approach makes this validator more reusable.
using System.ComponentModel.DataAnnotations;
namespace EmployeeManagement.Models.CustomValidators
{
public class EmailDomainValidator : ValidationAttribute
{
public string AllowedDomain { get; set; }
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
string[] strings = value.ToString().Split('@');
if (strings[1].ToUpper() == AllowedDomain.ToUpper())
{
return null;
}
return new ValidationResult($"Domain must be {AllowedDomain}",
new[] { validationContext.MemberName });
}
}
}
Using Custom Validation Attribute in Blazor
public class Employee
{
[EmailDomainValidator(AllowedDomain = "pragimtech.com")]
public string Email { get; set; }
}
- Use the custom validation attribute just like any other built-in validation attribute.
Email
property is decorated withEmailDomainValidator
attribute.AllowedDomain
property specifies the email domain that we want to validate against.
© 2020 Pragimtech. All Rights Reserved.