问题描述
public class UploadImageAlbum { [CustomFileValidator] public HttpPostedFileBase Images { get; set; } }
和我的CustomFileValidator类如下:
[AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =false)] public class CustomFileValidator : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext context) { const int maxContent = 1024 * 1024 * 50;//50 MB var sAllowedExt = new string[] { ".jpg", ".png" }; var file = value as HttpPostedFileBase; //Check for null if (file == null) { return new ValidationResult("Please select an image to upload"); } //Check for File Extension if (sAllowedExt.ToList().Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) { return new ValidationResult("Please Upload a valid file of type : " + string.Join(",", sAllowedExt)); } //Check for length of file if(file.ContentLength>maxContent) { return new ValidationResult("File is too large, maximum allowed size is :" + (maxContent / 1024) + "MB"); } return ValidationResult.Success; } }
和我的partialview如下:
@using (Html.BeginForm("UploadImages", "Admin", FormMethod.Post, htmlAttributes: new { id = "frmUploadImages", novalidate = "novalidate", autocomplete = "off", enctype = "multipart/form-data" })) { <div class="form-group"> <span class="btn btn-default btn-file-img"> Browse @Html.TextBoxFor(m => m.UIAModel.Images, new { type = "file", multiple = "multiple", data_charset = "file" }) </span> <span class="text-muted" id="filePlaceHolder">No files selected</span> @Html.ValidationMessageFor(m=>m.UIAModel.Images, null, htmlAttributes: new { @class= "invalid" }) </div> <div class="form-group"> <button class="btn btn-primary addImage pull-right"> <i class="fa fa-upload"></i> Upload </button> </div> }
和下面是如何在link上加载partialview上的partialview:
$('#page-inner').empty().load('/Admin/GetMediaUploadView', function () { $.validator.unobtrusive.parse($('form#frmUploadImages')); //Apply client validation for partialviews })
但即使在跟随所有步骤之后,它都没有显示任何消息和指向注意,如果我为同一个添加[Required]属性,它将运作良好,但自定义验证我从未显示任何消息.还有什么我要添加以使这个CustomValidator工作?我跟随 这篇文章 但仍然无法提供多大帮助.还如果有人让我知道如何更新这个model以便接受多个图像,它将具有很大的帮助.
推荐答案
为了获取客户端验证,必须
- 实现 iClientValidaTable 将添加关联的 data-val-*属性给您html,以及
- 您必须包含脚本以将方法添加到jQuery验证器.
本文是创建自定义客户端和服务器侧验证属性的好指南.
说明,您当前的属性相当有限,因为文件类型和大小是固定的,并且包含属性更灵活,以指定文件类型和最大文件大小,以便您可以使用它(例如)
[FileValidation(MaxSize="1024", FileType="jpg|png")] public HttpPostedFileBase Images { get; set; }
本文提供验证文件类型的属性的示例,但可以调整为包含MaxSize属性.
侧注:如果您加载动态内容,那么您应该首先将验证器设置为null
var form = $('form#frmUploadImages'); form.data('validator', null); $.validator.unobtrusive.parse(form);