filmov
tv
Custom validation attribute in asp net core

Показать описание
Text version of the video
Healthy diet is very important for both body and mind. We want to inspire you to cook and eat healthy. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking.
Slides
ASP.NET Core Text Articles & Slides
ASP.NET Core Tutorial
Angular, JavaScript, jQuery, Dot Net & SQL Playlists
ASP.NET Core built-in attributes
Required
Range
StringLength
Compare
Regular Expression
Custom Attribute in ASP.NET Core
If you have a complex validation requirement that you cannot implement using the built-in attributes, you can create a custom validation attribute and reuse it in your project or even in multiple projects if you create it in a separate class library project.
Custom Validation Attribute Example
ValidationAttribute class in ASP.NET Core
To create a custom validation attribute, create a class that derives from the built-in abstract ValidationAttribute class and override IsValid() method.
public class ValidEmailDomainAttribute : ValidationAttribute
{
private readonly string allowedDomain;
public ValidEmailDomainAttribute(string allowedDomain)
{
}
public override bool IsValid(object value)
{
string[] strings = value.ToString().Split('@');
return strings[1].ToUpper() == allowedDomain.ToUpper();
}
}
Using the Custom Validation Attribute
public class RegisterViewModel
{
public string Email { get; set; }
// Other Properties
}
Use the custom validation attribute just like any other built-in validation attribute.
Email property is decorated with ValidEmailDomain attribute which is our custom validation attribute.
AllowedDomain property specifies the email domain that we want to validate against.
ErrorMessage property specifies the error message that should be displayed if the validation failes.
The ErrorMessage property is inherited from the built-in base class ValidationAttribute.
The validation error message is then picked up and displayed by the built-in validation tag helper.
Комментарии