【问题标题】:ASP.NET MVC3 - Custom validation attribute -> Client-side brokenASP.NET MVC3 - 自定义验证属性 -> 客户端损坏
【发布时间】:2011-08-05 11:55:15
【问题描述】:

我也在尝试使用客户端验证来实现自定义验证属性。

我的属性如下:

public class FileSize : ValidationAttribute, IClientValidatable
{
    private readonly int _size;

    public FileSize(int size)
    {
        ErrorMessage = "Invalid size.";
        _size = size;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "fileSize",
            ErrorMessage = ErrorMessage
        };

        rule.ValidationParameters["size"] = _size;

        yield return rule;
    }

    public override bool IsValid(object value)
    {
        return ((HttpPostedFileBase) value).ContentLength < _size;
    }
}

并且脚本包含在我的视图中如下所示:

<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $.validator.unobtrusive.adapters.addSingleVal('fileSize', 'size');
    });
</script>

问题是,即使包含所有这些脚本和注册新适配器的函数,客户端验证仍然无法正常工作,它只是继续使用服务器端验证......

有什么想法吗?

【问题讨论】:

  • 您找到解决方案了吗?如果有,可以分享一下吗?
  • Bump:我实际上正在寻找完全相同类型的验证器(文件大小)。你找到解决办法了吗??

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


【解决方案1】:

您缺少一些 JavaScript。

看看他的Advanced ASP.NET MVC 3谈话中的Brad Wilsons"greater" example

其中的一些源代码:

(function ($) {
$.validator.addMethod("jqgreater", function (value, element, params) {
    var thisValue, otherValue;
    if (this.optional(element)) { // No value is always valid
        return true;
    }

    thisValue = parseInt(value);
    otherValue = parseInt($(params).val());
    return thisValue > otherValue;
});

function getModelPrefix(fieldName) {
    return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}

function appendModelPrefix(value, prefix) {
    if (value.indexOf("*.") === 0) {
        value = value.replace("*.", prefix);
    }
    return value;
}

$.validator.unobtrusive.adapters.add("greater", ["other"], function (options) {
    var prefix = getModelPrefix(options.element.name),
        other = options.params.other,
        fullOtherName = appendModelPrefix(other, prefix),
        element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];

    options.rules["jqgreater"] = element;  // element becomes "params" in callback
    if (options.message) {
        options.messages["jqgreater"] = options.message;
    }
});
} (jQuery));

【讨论】:

猜你喜欢
  • 2012-03-06
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 2010-09-05
相关资源
最近更新 更多