【发布时间】:2018-09-05 08:49:25
【问题描述】:
我有一个使用 c# 在 ASP.NET MVC 5 框架之上编写的 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;
}
});
我可以看到适配器正在注册,但方法filesize没有被调用。
我希望当用户上传的文件超出设置的文件大小时显示错误消息,但是在附加文件时不会调用它。
我创建了一个存储库来显示$.validator.addMethod("filesize", function (value, element, param) 没有被调用,可以从MvcWithUnobtrusive 下载
我在这里做错了什么?如何使用$.validator 注册filesize 方法?
【问题讨论】:
-
当一个标签已经存在来覆盖这个名为
unobtrusive-validation的插件时,请不要创建一个名为jquery-validate-unobtrusive的新标签。 -
您在
console.log('Dumping the file object', lement.files[0]);中有一个简单的错字,导致您的脚本失败 - 它的element.files[0] -
附带说明,不要在单个属性中组合多个验证条件。你应该有一个单独的
FileTypeAttribute(例如参考How to validate file type of HttpPostedFileBase attribute in Asp.Net MVC 4?) -
请注意,这些脚本不应包含在
$(document).ready()中,以防您这样做 -
刚刚看了你的回购。您有
Picture的隐藏输入 - 默认情况下不验证隐藏输入(但您可以覆盖验证器以包含它们 - 以 attaching jquery validation to replacement element 为例)
标签: jquery asp.net-mvc-5 jquery-validate unobtrusive-validation