How to fire a custom validator in client side? This is what i have till now:
My validation class:
public class AlmostEqual : ValidationAttribute, IClientValidatable { private readonly string _otherProperty; private readonly float _myPercent; public AlmostEqual(string otherProperty,float percent) { _otherProperty = otherProperty; _myPercent = percent; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var property = validationContext.ObjectType.GetProperty(_otherProperty); var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null); dbEntities db = new dbEntities(); Metal metal = db.Metals.Find(Convert.ToInt32(otherPropertyValue)); double _unitWeight = metal.UnitWeight; double _percent = metal.UnitWeight * (_myPercent / 100); double myProperty = double.Parse(value.ToString()); bool result = myProperty >= _unitWeight - _percent && myProperty <= _unitWeight + _percent; if (!result) { return new ValidationResult(string.Format( CultureInfo.CurrentCulture, FormatErrorMessage(validationContext.DisplayName), new[] { _otherProperty } )); } return null; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "almostequal", }; rule.ValidationParameters.Add("other", _otherProperty); yield return rule; } }
Code from Metdata class:
[Required] [AlmostEqual("IDMetal",5,ErrorMessage="Weight do not correspond with dimensions.")] public Nullable<double> UnitWeight { get; set; } }
In view I added this js:
<script type="text/javascript"> $.validator.unobtrusive.adapters.addBool("almostequal", "Range"); </script>
My webconfig contains:
<add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" />
I get the error:
Uncaught TypeError: Cannot read property 'call' of undefined in file jquery.validate.min.js at line 27