In this commodity I volition explain with an instance, how to perform Client Side validation of HTML Fileupload element (<input type = "file" />) using Data Annotations in Model class and jQuery in ASP.Internet MVC Razor.

HTML Fileupload chemical element validation will allow upload of just 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 Customer Side Validation

Delight refer the following article for consummate information on how to configure Bundles and enable Client Side validation in ASP.Net MVC project.

Note : Past default the validation done using Information Annotation attributes is Server Side. And hence to make it work Client Side, the Customer Side validation must exist enabled.

Regular Expression

The following Regular Expression is used for validating the selected file in HTML Fileupload chemical element using its extension.

The Regular Expression can be modified to be used for multiple File extensions by simply calculation 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 Give-and-take Document and PDF files only

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

Regular Expression for allowing Image files only

([a-zA-Z0-ix\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)$

Model

The following Model grade consists of one holding PostedFile to which the post-obit validation Information Annotation attributes have been applied.

1. Required Data Notation attribute.

2. RegularExpression Information Notation aspect.

The RegularExpression Information Note attribute accepts the Regular Expression as get-go parameter. The Regular expression volition allow only Epitome files of blazon PNG, JPG and GIF.

The Required Data Annotation and the RegularExpression Data Annotation attributes accept been specified with a property Mistake Bulletin with a string value. As the name suggests, this string value will be displayed to the user when the corresponding 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 { become ; set ; }

}

Namespaces

You will need to import the following namespace.

Controller

The Action method Index by default supports the Go operation and hence another overridden method for Post functioning is created which accepts the parameter of type HttpPostedFileBase.

Notation : The name of the HttpPostedFileBase parameter and the name of Model Property must exist exact same, otherwise the HttpPostedFileBase parameter will be Cypher.

First a cheque is performed whether Directory (Folder) exists if non so the Directory (Binder) is created and then the file is saved to the Directory (Binder).

public class HomeController : Controller

{

// GET: Home

    [ HttpGet ]

public ActionResult Index()

    {

return View();

    }

    [ HttpPost ]

public ActionResult Index( HttpPostedFileBase postedFile)

    {

cord path = Server.MapPath( "~/Uploads/" );

if (! Directory .Exists(path))

        {

Directory .CreateDirectory(path);

        }

if (postedFile != null )

        {

cord fileName = Path .GetFileName(postedFile.FileName);

            postedFile.SaveAs(path + fileName);

            ViewBag.Message += cord .Format( "<b>{0}</b> uploaded.<br />" , fileName);

        }

return View();

    }

}

View

Inside the View, in the very start line the FileModel course is declared every bit Model for the View.

The View consists of an HTML Course which has been created using the Html.BeginForm method with the following parameters.

ActionName Proper name of the Action. In this example the proper name is Index.

ControllerName – Proper noun of the Controller. In this case the proper name is Home.

FormMethod – Information technology specifies the Form Method i.e. Get or POST. In this case it will be set up to Mail.

HtmlAttributes – This array allows to specify the additional Form Attributes. Hither nosotros demand to specify enctype = "multipart/class-information" which is necessary for uploading Files.

Within the View, the following two HTML Helper functions are used:-

one. Html.TextBoxFor – Creating a Fileupload element for the Model holding. The blazon aspect is specified every bit file and hence the output is an HTML Fileupload chemical element instead of TextBox.

2. Html.ValidationMessageFor – Displaying the Validation bulletin for the property.

There is likewise Submit push button which when clicked, the Form gets submitted.

The jQuery and the jQuery Validation script bundles are rendered at the cease of the Model using the Scripts.Render part.

@model FileUpload_Validation_MVC.Models.FileModel

@{

    Layout = null ;

}

< !DOCTYPE html >

< html >

< caput >

< meta proper name ="viewport" content ="width=device-width" />

< championship > Index </ title >

< style type ="text/css">

body

        {

font-family : Arial ;

font-size : 10pt ;

        }

.fault {

color : reddish ;

        }

</ style >

</ head >

< body >

< div >

@ using (Html.BeginForm( "Index" , "Home" , FormMethod.Post, new { enctype = "multipart/form-data" }))

        {

< span > Select File: </ bridge >

@Html.TextBoxFor(grand => m.PostedFile, new { blazon = "file" })

< br />

@Html.ValidationMessageFor(k => m.PostedFile, "" , new { @class = "error" })

< hr />

< input type ="submit" value ="Upload" />

< br />

< span way =" color : greenish"> @ Html.Raw(ViewBag.Message) </ span >

        }

</ div >

</ trunk >

@ Scripts.Render( "~/bundles/jquery" )

@ Scripts.Return( "~/bundles/jqueryval" )

</ html >

Screenshot

Fileupload validation using Model Data Annotations in ASP.Net MVC

Downloads