Sunday, November 6, 2016

MVC 5: Custom DataAnnotation with Client Side Validation

  [Required]  
     [MinValue(50, "Number", "minimum value is 50")]  
     public int Number { get; set; }  

Custom ValidationAttribute Code:

 public class MinValueAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute, System.Web.Mvc.IClientValidatable  
   {  
     private String PropertyName { get; set; }  
     private readonly int _minValue;  
     public MinValueAttribute(int minValue, String propertyName, String errormessage)  
     {  
       this._minValue = minValue;  
       this.PropertyName = propertyName;  
       this.ErrorMessage = errormessage;  
     }  
     public override bool IsValid(object value)  
     {  
       return (int)value >= _minValue;  
     }  
 }  

Override the method GetClientValidationRules to add data-val attributes to html5 code.

 public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)  
     {  
       var modelClientValidationRule = new ModelClientValidationRule  
       {  
         ValidationType = "minvalue",  
         ErrorMessage = this.ErrorMessage,   
       };  
       modelClientValidationRule.ValidationParameters.Add("minval", this._minValue);  
       yield return modelClientValidationRule;  
     }  
Client Side code: add this code in files called minvalValidation.js
 $.validator.addMethod("minvalue", function (value, element, params) {  
   var minLength = $(element).attr("data-val-minvalue-minval");  
   if (value < minLength) {  
     var message = $(element).attr('data-val-minvalue');  
     $.validator.messages.minvalue = message;  
     return false;  
   }  
   return true;  
 });  
 $.validator.unobtrusive.adapters.add('minvalue', function (options) {  
   options.rules['minvalue'] = options.params;  
   if (options.message != null) {  
     $.validator.messages.minvalue = options.message;  
   }  
 });