Search code examples
jqueryasp.net-mvcfile-uploadunobtrusive-validationunobtrusive-javascript

Validating HttpPostedFileBase on client side with jquery unobtrusive


I got jquery (original, validate & unobtrusive) on my site. I've extended a validation attribute which works on server side, but I can not for the life of me get it to work on client side. What am I missing?

My model looks like this:

[Display(Name = "UploadFile"), DataType(DataType.Upload)]
[ValidateFile]
public IEnumerable<HttpPostedFileBase> MyImage { get; set; }

I have added this attribute extension to my model:

public class ValidateFileAttribute : ValidationAttribute 
{
    public override bool IsValid(object value)
    {
        int MaxContentLength = 1024 * 1024 * 10; //10 MB
        string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
        var files = value as IEnumerable<HttpPostedFileBase>;

        foreach (var file in files)
        {
            if (file == null)
            {
                return false;
            }
            else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = Resources.ResourcesAdvert.AdvertUploadFileExtensionErrorShorter + string.Join(", ", AllowedFileExtensions);
                return false;
            }
            else if (file.ContentLength > MaxContentLength)
            {
                ErrorMessage = Resources.ResourcesAdvert.AdvertUploadFileTooBig + (MaxContentLength / 1024).ToString() + "MB";
                return false;
            }
            else
            {
                return true;
            }
        }
        return false;
    }
}

I've got a view like this:

@Html.LabelFor(x => x.MyImage)

<input type="file" name="MyImage[0]" id="MyImage1" />
<input type="file" name="MyImage[1]" id="MyImage2" />
<input type="file" name="MyImage[2]" id="MyImage3" />

@Html.ValidationMessageFor(x => x.MyImage)

My controller is working fine and it works to upload images if they are valid. Any ideas how I could proceed?

EDIT: I've also tried to use this , but that didn't work for me client side either and I could not manage to customize an error message.


Solution

  • As there were no answer I'll share some information in case someone else comes across the same problem I did.

    I eventually solved it by following the link @Stephen Muecke provided (here). My problem was with not configuring the javascript properly since I didn't understand where to put each variable.