MVC 中的自定义验证未在部分视图上执行
Custom validation in MVC not executing on partial views
所以我有强类型的文件上传输入,下面是 model class
public class UploadImageAlbum
{
[CustomFileValidator]
public HttpPostedFileBase Images { get; set; }
}
我的CustomFileValidator
class如下:
[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
:
的 click
上加载 partialview
$('#page-inner').empty().load('/Admin/GetMediaUploadView', function () {
$.validator.unobtrusive.parse($('form#frmUploadImages'));
//Apply client validation for partialviews
})
但即使在执行了所有步骤之后,它也没有显示任何消息,需要注意的是,如果我为此添加 [Required]
属性,它会很好地工作,但自定义验证我有什么从不显示任何消息。我还需要添加什么才能使 CustomValidator
正常工作?我关注了 this post 但仍然帮不上什么忙。另外,如果有人让我知道如何更新此 model
以接受多张图片,那将有很大帮助。
为了获得客户端验证,您的属性必须
- 实施 IClientValidatable 这将添加相关的
data-val-*
属于你 html,
- 您必须包含脚本才能将方法添加到 jQuery 验证器。
This article 是创建自定义客户端和服务器端验证属性的好指南。
另请注意,您当前的属性相当有限,因为文件类型和大小是固定的,包含属性以指定文件类型和最大文件大小会更灵活,这样您就可以将其用作(比如)
[FileValidation(MaxSize="1024", FileType="jpg|png")]
public HttpPostedFileBase Images { get; set; }
This article 提供了一个验证文件类型的属性示例,但可以修改为包括 MaxSize
属性.
旁注:如果您加载动态内容,则应首先将验证器设置为 null
var form = $('form#frmUploadImages');
form.data('validator', null);
$.validator.unobtrusive.parse(form);
所以我有强类型的文件上传输入,下面是 model class
public class UploadImageAlbum
{
[CustomFileValidator]
public HttpPostedFileBase Images { get; set; }
}
我的CustomFileValidator
class如下:
[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
:
click
上加载 partialview
$('#page-inner').empty().load('/Admin/GetMediaUploadView', function () {
$.validator.unobtrusive.parse($('form#frmUploadImages'));
//Apply client validation for partialviews
})
但即使在执行了所有步骤之后,它也没有显示任何消息,需要注意的是,如果我为此添加 [Required]
属性,它会很好地工作,但自定义验证我有什么从不显示任何消息。我还需要添加什么才能使 CustomValidator
正常工作?我关注了 this post 但仍然帮不上什么忙。另外,如果有人让我知道如何更新此 model
以接受多张图片,那将有很大帮助。
为了获得客户端验证,您的属性必须
- 实施 IClientValidatable 这将添加相关的
data-val-*
属于你 html, - 您必须包含脚本才能将方法添加到 jQuery 验证器。
This article 是创建自定义客户端和服务器端验证属性的好指南。
另请注意,您当前的属性相当有限,因为文件类型和大小是固定的,包含属性以指定文件类型和最大文件大小会更灵活,这样您就可以将其用作(比如)
[FileValidation(MaxSize="1024", FileType="jpg|png")]
public HttpPostedFileBase Images { get; set; }
This article 提供了一个验证文件类型的属性示例,但可以修改为包括 MaxSize
属性.
旁注:如果您加载动态内容,则应首先将验证器设置为 null
var form = $('form#frmUploadImages');
form.data('validator', null);
$.validator.unobtrusive.parse(form);