MVC中的自定义验证不在部分视图上执行

时间:2015-10-24 17:09:09

标签: c# asp.net-mvc asp.net-mvc-4 custom-validators

所以我的文件上传输入是强类型的,下面是model class

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>&nbsp;
            <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>
}

及以下是我在partialview的{​​{1}}加载click的方式:

link

但是即使在完成所有步骤之后,它也没有显示任何消息,并指出要注意的是,如果我为它添加$('#page-inner').empty().load('/Admin/GetMediaUploadView', function () { $.validator.unobtrusive.parse($('form#frmUploadImages')); //Apply client validation for partialviews }) 属性,它将运行良好,但自定义验证我从未显示过任何消息。我还需要添加什么才能使[Required]正常工作?我跟着 this post ,但仍然没有多大帮助。另外,如果有人让我知道如何更新此CustomValidator以便接受多张图片,那将会有很大的帮助。

1 个答案:

答案 0 :(得分:2)

要获得客户端验证,您的属性必须

  1. 实施IClientValidatable,它将添加相关联的 {h}的data-val-*属性和
  2. 您必须包含脚本以向jQuery验证器添加方法。
  3. This article是创建自定义客户端和服务器端验证属性的良好指南。

    另请注意,您当前的属性相当有限,因为文件类型和大小是固定的,并且包含属性以指定文件类型和最大文件大小会更灵活,以便您可以将其用作(例如)< / p>

    [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);