Custom Client Validation:-

MVC application provides option to create your own validation annotation by inheriting “ValidationAttribute” abstract class. To support client-side validation you need your attribute to implement an interface “IClientValidatable”.

“IClientValidatable” defines single method “GetClientValidationRules”, so framework will make sure that validation object carries the metadata or rules to the client for client validation.

Consider the below custom validation attribute support client validation

    
publicclassMaxWordsAttribute : ValidationAttribute,
IClientValidatable
{
    int _maxWords;

    public MaxWordsAttribute(int maxwords)
    {
        _maxWords = maxwords;
    }

    protectedoverrideValidationResult IsValid(object value, ValidationContext validationContext)
    {
        ///Add your validation logic
        ///
    }

    publicIEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = newModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationParameters.Add("wordcount", _maxWords);
        rule.ValidationType = "maxwords";
        yieldreturn rule;
    }
}

    
    

MVC framework will take the rules given in “GetClientValidationRules” method and serialize the information into data dash attribute on the client

Model:

    
publicclassEmployeeModel
    {
        [ScaffoldColumn(false)]
        publicstring ID { get; set; }

        [Required]              
        publicstring Name { get; set; }

        ..

        [MaxWords(10)]
        [Required]
        publicstring Comments { get; set; }
    }


    
    

Render markup at client side:

    
<inputclass="text-box single-line"
data-val="true"
data-val-maxwords="The field Comments is invalid."
data-val-maxwords-wordcount="10"
data-val-required="The Comments field is required."
id="Comments"
name="Comments"
type="text"value=""/>