Custom validation in MVC not executing on partial views

一曲冷凌霜 提交于 2019-12-20 07:19:13

问题


So I have file uploading input which is strongly typed and below is the model class

public class UploadImageAlbum
{
    [CustomFileValidator]
    public HttpPostedFileBase Images { get; set; }
}

and my CustomFileValidator class is as below:

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

and my partialview is as below:

@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>
}

and below is how I load partialview on click of a link:

$('#page-inner').empty().load('/Admin/GetMediaUploadView', function () {
      $.validator.unobtrusive.parse($('form#frmUploadImages'));
      //Apply client validation for partialviews
})

But even after following all the steps, it isn't displaying any message and point to note is, if I add [Required] attribute for the same, it will work well, but custom validation what I have never displays any message. What else I have to add to make this CustomValidator to work? I followed this post but still could not be of much help. Also if anyone let me know how to update this model so as to accept multiple images, it will be of great help.


回答1:


In order to get client side validation, your attribute must

  1. implement IClientValidatable which will add the associated data-val-* attributes to you html, and
  2. you must include scripts to add methods to the jQuery validator.

This article is a good guide to creating custom client and server side validation attributes.

Note also your current attribute is rather limited in that the file types and size are fixed, and it would be more flexible to include properties to specify the file types and maximum file size so that you could use it as (say)

[FileValidation(MaxSize="1024", FileType="jpg|png")]
public HttpPostedFileBase Images { get; set; }

This article provide an example of an attribute that validates the file type, but could be adapted to include the MaxSize property.

Side note: If your loading dynamic content, then you should first set the validator to null

var form = $('form#frmUploadImages');
form.data('validator', null);
$.validator.unobtrusive.parse(form);


来源:https://stackoverflow.com/questions/33320969/custom-validation-in-mvc-not-executing-on-partial-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!