In this article I will explain with an example, how to perform Client Side validation of HTML Fileupload element (<input type = “file” />) using Data Annotations in Model class and jQuery in ASP.Net MVC Razor.
HTML Fileupload element validation will allow upload of only certain files by filtering them using their extensions. This filtering of files will be done using the RegularExpression Data Annotation attribute in Model class.
Configuring Bundles and enabling Client Side Validation
Please refer the following article for complete information on how to configure Bundles and enable Client Side validation in ASP.Net MVC project.
Note: By default the validation done using Data Annotation attributes is Server Side. And hence to make it work Client Side, the Client Side validation must be enabled.
Regular Expression
The following Regular Expression is used for validating the selected file in HTML Fileupload element using its extension.
The Regular Expression can be modified to be used for multiple File extensions by simply adding and removing the extensions.
Note: The File Extensions must be separated by Pipe (|) character and must be prefixed with Dot (.) character.
Regular Expression for allowing Word Document and PDF files only
Regular Expression for allowing Image files only
Regular Expression for allowing Text files only
Regular Expression for allowing Excel files only
The following Model class consists of one property PostedFile to which the following validation Data Annotation attributes have been applied.
1. Required Data Annotation attribute.
2. RegularExpression Data Annotation attribute.
The RegularExpression Data Annotation attribute accepts the Regular Expression as first parameter. The Regular expression will allow only Image files of type PNG, JPG and GIF.
The Required Data Annotation and the RegularExpression Data Annotation attributes have been specified with a property Error Message with a string value. As the name suggests, this string value will be displayed to the user when the respective validation fails.
public class FileModel
    [Required(ErrorMessage = "Please select file.")]
    [RegularExpression(@"([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$", ErrorMessage = "Only Image files allowed.")]
    public HttpPostedFileBase PostedFile { get; set; }
You will need to import the following namespace.
using System.IO;
The Action method Index by default supports the GET operation and hence another overridden method for POST operation is created which accepts the parameter of type HttpPostedFileBase.
Note: The name of the HttpPostedFileBase parameter and the name of Model Property must be exact same, otherwise the HttpPostedFileBase parameter will be NULL.
First a check is performed whether Directory (Folder) exists if not then the Directory (Folder) is created and then the file is saved to the Directory (Folder).
Finally a message is displayed to the user using ViewBag. For more details on displaying message using ViewBag, please refer my article Display (Pass) String Message from Controller to View in ASP.Net MVC.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        return View();
    public ActionResult Index(HttpPostedFileBase postedFile)
        string path = Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        if (postedFile != null)
            string fileName = Path.GetFileName(postedFile.FileName);
            postedFile.SaveAs(path + fileName);
            ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", fileName);
        return View();
Inside the View, in the very first line the FileModel class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionNameName of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.2
Inside the View, the following two HTML Helper functions are used:-
1. Html.TextBoxFor – Creating a Fileupload element for the Model property. The type attribute is specified as file and hence the output is an HTML Fileupload element instead of TextBox.
2. Html.ValidationMessageFor – Displaying the Validation message for the property.
There is also Submit button which when clicked, the Form gets submitted.
The jQuery and the jQuery Validation script bundles are rendered at the end of the Model using the Scripts.Render function.
@model FileUpload_Validation_MVC.Models.FileModel
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
    <style type="text/css">
            font-family: Arial;
            font-size: 10pt;
        .error {
            color: red;
        @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
            <span>Select File:</span>
            @Html.TextBoxFor(m => m.PostedFile, new { type = "file"})
            @Html.ValidationMessageFor(m => m.PostedFile, "", new { @class = "error" })
            <input type="submit" value="Upload"/>
            <span style="color:green">@Html.Raw(ViewBag.Message)</span>
Fileupload validation using Model Data Annotations in ASP.Net MVC