自定义验证器asp.net MVC 4的客户端验证

时间:2014-02-19 11:16:38

标签: jquery asp.net-mvc validation jquery-validate data-annotations

我有一个自定义服务器端验证器可以工作,但我很难让客户端工作。这是我到目前为止所拥有的。

验证人检查输入的值是否至少是输入的另一个值的百分比。

public sealed class PercentageOfAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string sourcePropertyName;
    private readonly int minimumPercentage;

    public PercentageOfAttribute(string sourcePropertyName, int minimumPercentage)
    {
        this.sourcePropertyName = sourcePropertyName;
        this.minimumPercentage = minimumPercentage;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var propertyName = validationContext.ObjectType.GetProperty(this.sourcePropertyName);
        if (propertyName == null)
            return new ValidationResult(String.Format("Uknown property {0}", this.sourcePropertyName));

        int propertyValue = (int)propertyName.GetValue(validationContext.ObjectInstance, null);

        var minValue = (propertyValue / 100) * this.minimumPercentage;
        if ((int)value > minValue)
            return ValidationResult.Success;

        return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));

    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessageString,
            ValidationType = "percentageof"
        };
        rule.ValidationParameters["propertyname"] = this.sourcePropertyName;
        rule.ValidationParameters["minimumpercentage"] = this.minimumPercentage;
        yield return rule;
    }
}

客户端的javascript ...

jQuery.validator.addMethod("percentageof", function (value, element, params) {
    var propertyname = params['propertyname'];
    var minimumpercentage = param['minimumpercentage'];
    var propValue = $('#' + propertyname).val();
    var minValue = (propValue / 100) * minimumpercentage;
    if (value >= minValue) {
        return true;
    }
    return false;
});
jQuery.validator.unobtrusive.adapters.add("percentageof", ["propertyname", "minimumpercentage"], function (options) {
    options.rules['propertyname'] = options.params.propertyname;
    options.rules['minimumpercentage'] = options.params.minimumpercentage;
    options.message['percentageof'] = options.message;
});

我调试了addapters.add函数,这是传递正确的数据。 “data-val-percentageof- *”值出现在html中并具有正确的值。

我目前得到的javascript错误是“$ .validator.methods [method] is undefined”。我认为这意味着我没有正确设置客户端验证器。我已经阅读了无数的例子和教程,但似乎无法找出有效的组合。

如果我删除所有自定义内容,则默认的客户端验证工作正常。

任何人都可以帮我看看我做错了吗?

修改

渲染的html如下

<div class="form-group">
<label class="col-sm-3 control-label" for="PurchasePrice">Purchase Price (£36,000 minimum) *</label>
<div class="col-sm-6">
    <input id="PurchasePrice" class="form-control valid" type="text" value="0" name="PurchasePrice" data-val-required="Please enter a Purchase Price" data-val-range-min="36000" data-val-range-max="2147483647" data-val-range="Please enter at least £36,000" data-val-number="The field Purchase Price (£36,000 minimum) * must be a number." data-val="true">
    <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="PurchasePrice"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="Deposit">Available Deposit (30% minimum)*</label>
<div class="col-sm-6">
    <input id="Deposit" class="form-control" type="text" value="0" name="Deposit" data-val-required="Please enter an Available Deposit" data-val-percentageof-propertyname="PurchasePrice" data-val-percentageof-minimumpercentage="30" data-val-percentageof="Please enter value that is at least 30% of the purchase price" data-val-number="The field Available Deposit (30% minimum)* must be a number." data-val="true">
    <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Deposit"></span>
</div>
</div>

1 个答案:

答案 0 :(得分:1)

我设法通过更改... adapters.add函数的格式来实现此目的

jQuery.validator.addMethod("percentageof", function (value, element, params) {
  var propertyname = params['propertyname'];
  var minimumpercentage = params['minimumpercentage'];
  var propValue = $('#' + propertyname).val();
  var minValue = (propValue / 100) * minimumpercentage;
  if (value >= minValue) {
    return true;
  }
  return false;
});
jQuery.validator.unobtrusive.adapters.add("percentageof", ["propertyname", "minimumpercentage"], function (options) {
  options.rules["percentageof"] = options.params;
  if (options.message) {
    options.messages['percentageof'] = options.message;
  }
});

我错误地试图将参数作为规则添加!!代码的addMethod部分也有一个拼写错误。