I have a file upload feature in my MVC 3 web application and I’m trying to validate FileSize and FileType using those attributes:
[FileSize(1048576, ErrorMessage = "The image is too big. It should be up to 1MB")]
[FileType(MimeTypes.Image.Jpg, MimeTypes.Image.Jpeg, MimeTypes.Image.Png, "image/pjpeg", "image/x-png", ErrorMessage = "Your image must be a JPG/JPEG or PNG up to 1MB.")]
public HttpPostedFileBase File { get; set; }
HTML is as follows:
<input type="file" size="20" name="File" />
@Html.ValidationMessageFor(x => x.File)
Everything works perfect when the file is selected. But if there is no file selected, I still get FileSize or FileType validation fired and validation errors. How can I avoid this since I don’t want File to be required on POST?
You will have to modify the
FileSizeandFileTypecustom validation attributes so that do not perform any validation if the value is null. For example:And it is via the
[Required]attribute that you could make the file required.