I am using asp.net mvc3. I am using dataannotation and Jquery unobstrusive for server side and client side validation. How to validate fileupload which accepts only image file extensions.Need to work exactly same as others. Do I need to create a custom validator for server side and client side? Thanks in advance
1 Answer
You can do something like this: If u are using property in model
public class ValidateFileAttribute : ValidationAttribute { public override bool IsValid(object value) { int MaxContentLength = 1 * 1024 * 700; //3 MB string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
var file = value as HttpPostedFileBase;
if (file == null)
return false;
else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ErrorMessage = "Please upload Your image of type: " + string.Join(", ", AllowedFileExtensions);
return false;
}
else if (file.ContentLength > MaxContentLength)
{
ErrorMessage = "Your image is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
return false;
}
else
return true;
}
}
<input type=file