ASP.NET MVC客户端验证自定义属性

时间:2014-09-10 09:37:23

标签: c# jquery asp.net-mvc validation

如何在客户端触发自定义验证器? 这就是我现在所拥有的:

我的验证课程:

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


}

Metdata类的代码:

        [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" />

我收到错误:

未捕获的TypeError:无法读取属性&#39; call&#39;未定义的文件 第27行的jquery.validate.min.js

1 个答案:

答案 0 :(得分: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;
});

关于规则:

此HTML元素的jQuery规则数组。期望适配器将项添加到此规则数组中,以用于要附加的特定jQuery Validate验证器。名称是jQuery Validate规则的名称,值是jQuery Validate规则的参数值。