MVC provides you to create your own custom Annotation for validation purpose. You can create the custom annotation by inheriting “ValidationAttribute” abstract class.
Consider you have to check the user input such that only specific set of words should be accepted from user. Below code create custom attribute which validate the user input data based on maximum no of words defined.
using System.ComponentModel.DataAnnotations ;
public class MaxWordsAttribute:ValidationAttribute
{
int _maxWords;
public MaxWordsAttribute(int maxwords)
{
_maxWords = maxwords;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
///Add your validation logic
///
}
}
Model class:
public class EmployeeModel
{
[ScaffoldColumn(false)]
public string ID { get; set; }
[Required]
public string Name { get; set; }
[MaxWords (10)]
public string Comments { get; set; }
}