File type and extension validation with jQuery unobtrusive validation

1.2k Views Asked by At

I am currently trying to validate a file that will be uploaded onto a page. I am wanting to be able to validate that the file type is a .doc,.docx,.txt,.pdf,.rtf and that the size is 4 mb or less. I tried to use regular expression to validate the type with the following code.

     [RegularExpression(@"(^.*\.(rtf|doc|docx|pdf)$", ErrorMessage =@"Please upload a (.pdf, .doc, .docx, .txt, or .rtf) file")]

I then tried to validate the file size and type by creating the following class

     public class ValidateFileAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        int MaxContentLength = 1024;
        string[] AllowedFileExtensions = new string[] { ".doc", ".docx", ".pdf", ".txt", ".rtf" };

        var file = value as HttpPostedFileBase;

        if (file == null)
            return false;

        else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
        {
            ErrorMessage = "Upload File Type: " + string.Join(", ", AllowedFileExtensions);
            return false;
        }

        else if (file.ContentLength > MaxContentLength)
        {
            ErrorMessage = "The Size of the file is too large : " + (MaxContentLength / 1024).ToString() + "MB";
            return false;
        }

        else
            return true;
    }

}

(I understand that the 1024 will not allow me to upload a very large file but for testing reasons I left it at that to see if it would work).

In the view I used @Html.TextBoxFor(m => m.CV.File, new { type="file"}) @Html.ValidationMessageFor(m => m.CV.File)

I am unsure of how to get the validation to work correctly, it won't allow me to input a different file type however, it doesn't recognize the correct file types either.

0

There are 0 best solutions below