1

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
  • Are you using any third party controls for fileupload or else just using <input type=file Commented Jan 18, 2013 at 9:44

1 Answer 1

1

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;
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.