本文介绍了ASP.NET MVC客户端验证的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在客户端触发自定义验证器?这是我到目前为止所拥有的:

How to fire a custom validator in client side?This is what i have till now:

我的验证班:

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类的代码:

Code from Metdata class:

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

在视图中,我添加了此js:

In view I added this js:

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

我的webconfig包含:

My webconfig contains:

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

我得到了错误:

未捕获的TypeError:无法读取文件中未定义的属性调用"第27行的jquery.validate.min.js

Uncaught TypeError: Cannot read property 'call' of undefined in filejquery.validate.min.js at line 27

推荐答案

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

我能在代码中发现的唯一区别是创建$.validator.unobtrusive.adapters.addBool函数的方式.参数有些不同,但是可能的问题是,您尚未定义适配器的规则部分.

The only difference I can spot in your code is the way you created the $.validator.unobtrusive.adapters.addBool function. The parameters are a little bit different but, maybe, the problem is just that you have not defined the rule part of your adapter.

尝试使用类似这样的内容:

Try using something like this:

$.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规则的参数值.

The jQuery rules array for this HTML element. The adapter is expected to add item(s) to this rules array for the specific jQuery Validate validators that it wants to attach. The name is the name of the jQuery Validate rule, and the value is the parameter values for the jQuery Validate rule.

这篇关于ASP.NET MVC客户端验证的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:29
查看更多