我有一个在MVC 5框架之上使用c#编写 ASP.NET Web项目。我正在使用jquery-validation-unobtrusive
包来建立客户端验证。我正在尝试添加一个名为filesize
的新规则,该规则检查附件的大小。
因此,当附件的大小大于允许的大小时,我想显示客户端大小错误消息。
我创建了 FileSizeAttribute 属性,以便能够在我的视图模型中用于装饰我的HttpPostedFileBase
属性,以设置允许的最大大小。CreatePerson 类显示了我如何使用它。
然后在我的javascript文件中,我添加了以下代码,以在jquery-validator中注册一个名为filesize的新方法。
型
[Required, FileSize(4000), AcceptedFileExtension("jpg|pdf|csv|text")]
public HttpPostedFileBase Picture { get; set; }
视图
<div class="form-group" id="Picture_Block">
<label class="control-label col-md-2" for="Picture">Picture</label>
<div class="col-md-10">
<div class="input-group uploaded-file-group max-input-width">
<label class="input-group-btn">
<span class="btn btn-default">
Browse
@Html.HiddenFor(x => x.Picture, new { @class= "hidden force-validaion", type = "file" })
</span>
</label>
<input class="form-control uploaded-file-name" readonly="" type="text">
</div>
@Html.ValidationMessageFor(x => x.Picture)
</div>
</div>
验证脚本
$.validator.addMethod("filesize", function (value, element, param) {
if (value === "") {
return true;
}
var maxBytes = parseInt(param);
if (element.files !== undefined && element.files[0] !== undefined && element.files[0].size !== undefined) {
console.log('Dumping the file object', element.files[0]);
var filesize = parseInt(element.files[0].size);
return filesize <= maxBytes;
}
return true;
});
然后我添加了一个名为 filesize 的新不显眼的适配器,以允许我将规则/消息添加到验证选项中,如下所示
$.validator.unobtrusive.adapters.add('filesize', ['maxfilesize'], function (options) {
// set the parameter
options.rules['filesize'] = options.params.maxfilesize;
if (options.message) {
// If there is a message, set it for the rule
options.messages['filesize'] = options.message;
}
});
我可以看到适配器正在注册,但未调用方法文件大小。
我希望当用户上传超过设置的文件大小时显示错误消息,但是在附加文件时不会调用它。
我创建了一个存储库来显示如何不调用$.validator.addMethod("filesize", function (value, element, param)
可以从 MvcWithUnobhisive 下载
我在这里做错了什么?如何向$.validator
注册filesize
方法?
Picture
的文件输入是隐藏的,默认情况下,不会验证隐藏的输入。
您可以通过包含以下脚本来覆盖默认值
$.validator.setDefaults({
ignore: []
});
或者,如果您有其他不想验证的隐藏元素,则可以为该元素指定一个类名(例如class="fileinput"
(并使用
$.validator.setDefaults({
ignore: ":hidden:not('.fileinput')"
});