【问题标题】:Client side validation for custom validator asp.net MVC 4自定义验证器 asp.net MVC 4 的客户端验证
【发布时间】:2014-03-19 16:32:47
【问题描述】:

我有一个可以工作的自定义服务器端验证器,但我正在努力让客户端工作。这是我目前所拥有的。

验证器正在检查输入的一个值是否至少占另一个输入值的百分比。

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] 未定义”。我认为这意味着我没有正确设置客户端验证器。我已经阅读了无数的示例和教程,但似乎无法找出一个有效的组合。

如果我删除所有自定义内容,则默认客户端验证可以完美运行。

谁能帮我看看我做错了什么?

编辑:

渲染出来的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>

【问题讨论】:

  • 由于这可能是一个 JavaScript 问题,显示浏览器看到的表单的相关 rendered HTML 标记会很有帮助。
  • 感谢您的回复 - 我已在上面的编辑中添加了 HTML。

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


【解决方案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部分也有错别字。

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多