2014-09-10 97 views
1

如何在客户端触发自定义验证器? 这是我到现在为止:自定义属性的ASP.NET MVC客户端验证

我的验证类:从Metdata类

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; 
    } 


} 

代码:

 [Required]   
     [AlmostEqual("IDMetal",5,ErrorMessage="Weight do not correspond with dimensions.")] 
     public Nullable<double> UnitWeight { get; set; } 
    } 

鉴于我加入这个js:

<script type="text/javascript"> 
     $.validator.unobtrusive.adapters.addBool("almostequal", "Range"); 
</script> 

我的webconfig包含:

<add key="ClientValidationEnabled" value="true" /> 
<add key="UnobtrusiveJavaScriptEnabled" value="true" /> 

我得到的错误:

遗漏的类型错误:无法读取属性文件中未定义“称之为” jquery.validate.min.js在第27行

+0

请看看: http://stackoverflow.com/questions/4747184/perform-client-side-validation-for-custom-attribute/4747466 – 2014-09-10 09:43:55

+1

的联系是这个职位。 – POIR 2014-09-10 09:45:55

+0

对不起,更新了正确的URL – 2014-09-10 09:48:29

回答

1

在这个看看: http://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/

我可以在代码中发现的唯一差别就是您创建$.validator.unobtrusive.adapters.addBool函数的方式。这些参数有点不同,但也许问题在于您没有定义适配器的规则部分。

尝试使用这样的:

$.validator.unobtrusive.adapters.add("almostequal", function (options) { 
    options.rules["almostequal"] = "#" + options.element.name.replace('.', '_'); // mvc html helpers 
    options.messages["almostequal"] = options.message; 
}); 

关于规则:

jQuery的规则阵列这个HTML元素。预计适配器将项添加到它想要附加的特定jQuery验证验证程序的规则数组中。该名称是jQuery Validate规则的名称,该值是jQuery Validate规则的参数值。

相关问题