In this article I will explain with an example, how to implement FileUpload validation using Model Data Annotation in ASP.Net MVC.
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 Regular Expression Data Annotation attribute in Model class.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

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

([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$
 

Regular Expression for allowing Image files only

([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$
 

Regular Expression for allowing Text files only

([a-zA-Z0-9\s_\\.\-:])+(.txt)$
 

Regular Expression for allowing Excel files only

([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$
 
 

Uploads Folder Location

The file will be saved inside the Directory (Folder) named Uploads of ASP.Net MVC project.
ASP.Net MVC: Fileupload validation using Model Data Annotations
 
 

Model

The following Model class consists of one property PostedFile
The property is decorated with the following Data Annotation attributes for performing validations.
1. Required Data Annotation attribute.
2. RegularExpression Data Annotation attribute.
Note: The Data Annotations attributes can be used with the Entity Data Model (EDM), LINQ to SQL, and other data models.
 
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 Regular Expression Data Annotation attributes have been specified with a property ErrorMessage 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 { getset; }
}
 
 

Namespaces

You will need to import the following namespace.
using System.IO;
 
 

Controller

The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

This Action method accepts an object of HttpPostedFileBase class as a parameter.
Note: The name of the HttpPostedFileBase parameter and the name of Model Property must be exact same, otherwise the HttpPostedFileBase parameter will be NULL.
 
Inside this Action method, first a check is performed whether the Folder (Directory) exists, if not then the Directory (Folder) is created.
After that, if object of HttpPostedFileBase class is not NULL then the selected file is saved to the Folder (Directory) named Uploads using SaveAs method of HttpPostedFileBase class.
Finally, the success message along with the file name is set into a ViewBag object.
Note: 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();
    }
 
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        string path = Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        if (postedFile != null)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            postedFile.SaveAs(path + fileName);
            ViewBag.Message += string.Format("{0} uploaded.
"
, fileName);
        }
 
        return View();
    }
}
 
 

View

HTML Markup

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.
ActionName Name 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.
 

Implementing Validation

The Form consists of the following two HTML Helper functions:-
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.ValidationSummary – Displaying the error message when the validation fails.
There is also an HTML SPAN element and a Submit Button which when clicked, the Form gets submitted.
The SPAN element is used for displaying success message set into a ViewBag object using Html.Raw Helper Method.
 

Enabling Client-Side validations

By default, the validations using Data Annotations and Model class is performed on Server Side.
In order to enable Client-Side validations, you will need to inherit the following script files.
1. jquery.min.js
2. jquery.validate.js
3. jquery.validate.unobtrusive.js
Once, the above files are inherited automatically, the Client-Side validations using Data Annotations is enabled.
@model FileUpload_Validation_MVC.Models.FileModel
 
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index""Home"FormMethod.Post, new { enctype "multipart/form-data" }))
    {
        <span>Select File:</span>
        @Html.TextBoxFor(m =>m.PostedFilenew { type = "file"})
        <br />
        @Html.ValidationMessageFor(m =>m.PostedFile""new { @class = "error" })
        <hr />
        <input type="submit" value="Upload" />
        <br />
        <span style="color:green">@Html.Raw(ViewBag.Message)</span>
    }
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>
</body>
</html>
 
 

Screenshot

ASP.Net MVC: Fileupload validation using Model Data Annotations
 
 

Downloads