Today we will learn about custom data annotation attribute validator in ASP.NET . Data annotation is used to validate and configure model. Validation comes to scene when users do not properly give input/provide data. And configuration is need for like in scenery where code first approach comes. I mean generating database from model entities.
Some example of validation attributes are “Required, Key, MinLength, MaxLength”. Following is the example how we use them.
public class BlogPost
{
[Required]
public string Title { get; set; }
[Required]
[MaxLength(8, ErrorMessage = "Too Long")]
public string Slug { get; set; }
[Required]
public string Description { get; set; }
}
Here you can see that according to above model, users can not leave blank field as 3 fields are required. The max length of Slug field can not not cross 30. If users try to bypass any of them ModelState will catch the error.
These attributes come from System.ComponentModel.DataAnnotations
. But now we will write our own custom validation attribute. It will be used to validate slug property from Post model. We will add our custom need that user must fulfill. Open your Mvc/Api project in editor and create a folder inside your project, I am naming the folder ValidationAttributes. Inside the folder create a C# class and name it SlugValidate.cs . Paste the following code inside the file.
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace CA.Core.Application.Contracts.ValidationAttributes
{
public class SlugValidate : ValidationAttribute
{
public SlugValidate() : base("{0} has one or many space character.")
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var txt = value.ToString();
if (txt != null && txt.Contains(' '))
{
var errorMessage = FormatErrorMessage((validationContext.DisplayName));
return new ValidationResult(errorMessage);
}
if (txt != null && txt.Count(c => char.IsLetterOrDigit(c) || (c == ',') || (c == '.') || (c == '-') || (c == '_') || (c == '=')) == txt.Length)
{
return ValidationResult.Success;
}
return new ValidationResult("Invalid slug. please enter only letter, numbers and hiphen(-)");
}
}
}
As we have added our own custom attribute. We can simply add the attribute name in model class on top of slug property.
public class BlogPost
{
[Required]
public string Title { get; set; }
[Required]
[SlugValidate]
[MaxLength(8, ErrorMessage = "Too Long")]
public string Slug { get; set; }
[Required]
public string Description { get; set; }
}
Now our custom validator should work .
Nicely Explained