In this article I will explain with an example, how to implement Fileupload validation using Model Data Annotation in ASP.Net Core (.Net Core) 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.
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 wwwroot Directory (Folder).
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
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 IFormFile PostedFile{ get; set; }
}
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 the IFormFile class object as a parameter.
Note: The name of the IFormFile parameter and the name of HTML FileUpload element must be exact same, otherwise the IFormFile 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 using IWebHostEnvironment interface.
After that, if object of IFormFile is not NULL then an object of FileStream class is created which accepts the path of the Folder (Directory) named Uploads as a parameter.
Then, using Copy method of IFormFile class which accepts the FileStream class object as parameter which saved the selected file to the Folder (Directory) named Uploads.
Finally, the success message along with the file name is set into a
ViewBag object.
public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
this.Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(IFormFile postedFile)
{
string wwwPath = this.Environment.WebRootPath;
string contentPath = this.Environment.ContentRootPath;
string path = Path.Combine(this.Environment.WebRootPath,"Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (postedFile != null)
{
string fileName = Path.GetFileName(postedFile.FileName);
using (FileStream stream = new FileStream(Path.Combine(path,fileName), FileMode.Create))
{
postedFile.CopyTo(stream);
ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", 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 following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – 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 a FileUpload element, two HTML SPAN and a Submit Button.
The FileUpload element has been set with the following Tag Helpers attribute:-
asp-for – The Model property to which validation will be performed. In this case PostedFile.
The HTML SPAN have been set with the following Tag Helpers attribute:-
asp-validation-for – Displaying the validation message for the Model property.
Another SPAN element will be used to display the success message set into a
ViewBag object using
Html.Raw Helper Method when file is saved.
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_Core.Models.FileModel
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-action="Index" asp-controller="Home" method="post" enctype="multipart/form-data">
<span>Select File:</span>
<input type="file" asp-for="PostedFile" name="PostedFile" />
<br />
<span asp-validation-for="PostedFile" style="color:red"></span>
<hr />
<input type="submit" value="Upload" />
<br />
<span style=" color:green">@Html.Raw(ViewBag.Message)</span>
</form>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.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
Downloads