Form Validations Using MVC

When we are defining Validations at the Model level first we need to import the name space,

using System.ComponentModel.DataAnnotations;

In this article we are going to discuss about some of the validation attributes.

  1. Required
  2. StringLength
  3. RegularExpression
  4. Range

We can also create our own custom validation attribute we will see in later article series.

Create an MVC Project,

Select Empty Template and Add MVC Folder Reference,

new

Add New Controller in Controllers folder,

Controller

Select MVC 5 Controller - Empty,

Empty

Give Controller Name as Home,

Home

Add a View,

Right click on the Action Name and add view.

view

Add the Employee Class in Model folder,

Class

Import the Namespace in Employee.cs
  1. using System.ComponentModel.DataAnnotations;  
  2. Define the Properties with DataAnnations attributes.  
  3. public class Employee  
  4. {  
  5.     [Required(AllowEmptyStrings = false, ErrorMessage = "Please Provide First Name")]  
  6.     [StringLength(20, MinimumLength = 5, ErrorMessage = "First Name Should be min 5 and max 20 length")]  
  7.     public String FirstName  
  8.     {  
  9.         get;  
  10.         set;  
  11.     }  
  12.     [Required(AllowEmptyStrings = false, ErrorMessage = "Please Provide Last Name")]  
  13.     [StringLength(20, MinimumLength = 5, ErrorMessage = "First Name Should be min 5 and max 20 length")]  
  14.     public String LastName  
  15.     {  
  16.         get;  
  17.         set;  
  18.     }  
  19.     [Required(AllowEmptyStrings = false, ErrorMessage = "Please Provide Eamil")]  
  20.     [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Please Provide Valid Email")]  
  21.     public String Email  
  22.     {  
  23.         get;  
  24.         set;  
  25.     }  
  26.     [Required(AllowEmptyStrings = false, ErrorMessage = "Please Provide Age")]  
  27.     [Range(25, 45, ErrorMessage = "Age Should be min 25 and max 45")]  
  28.     public int ? Age  
  29.         {  
  30.             get;  
  31.             set;  
  32.         }  
  33.         [Required(ErrorMessage = "Please Provide Gender")]  
  34.     public bool Gender  
  35.     {  
  36.         get;  
  37.         set;  
  38.     }  
  39. }  
code

In the above Employee Class we have FirstName, Last Name, Email, Age, Gender properties defined.

Required

Gets or Sets value that indicates whether an empty string is allowed or not.

value

In the Required attribute we have different type of properties.

AllowEmptyStrings:

AllowEmptyStrings is a Boolean property and it accepts true or false, by default it is false.

ErrorMessage:

ErrorMessage accepts string when validation fails on properties and it shows the error message to end user.

StringLength:

Gets or Sets Maximum length or Minimum length of characters to be allowed.

value

maximumLength:

It allows integer value and sets the maximum length of characters to be allowed.

minimumLength:

It allows integer value and sets the minimum length of characters to be allowed.

ErrorMessage:

ErrorMessage accepts string when validation fails on property and it shows the error message to end user.

Range:

Set the minimum or maximum value allowed to data filed,

range

Minimum:

It allows double data type and specifies the Minimum value to be allowed.

Maximum:

It allows double data type and specifies the Maximum value to be allowed.
ErrorMessage:

ErrorMessage accepts string when validation fails on property and it shows the error message to end user.

RegularExpression:

RegularExpression

Pattern:

It sets the regular expression for Email, Phone number, Card Numbers, etc...

ErrorMessage:

ErrorMessage accepts string when validation fails on property and shows the error message to end user.

Index.cshtml:
  1. @model FormValidations.Models.Employee  
  2. @  
  3. {  
  4.     ViewBag.Title = "Index";  
  5. }  
  6. @using(Html.BeginForm("""", FormMethod.Post, htmlAttributes: new  
  7. {  
  8.     @class = "form"  
  9. }))  
  10. { < div class = "form-group" > < label > First Name < /label>  
  11.     @Html.TextBoxFor(m => m.FirstName, null, htmlAttributes: new  
  12.     {  
  13.         @class = "form-control"  
  14.     })  
  15.     @Html.ValidationMessageFor(m => m.FirstName, ""new  
  16.     {  
  17.         @class = "text-danger"  
  18.     }) < /div> < div class = "form-group" > < label > Last Name < /label>  
  19.     @Html.TextBoxFor(m => m.LastName, null, htmlAttributes: new  
  20.     {  
  21.         @class = "form-control"  
  22.     })  
  23.     @Html.ValidationMessageFor(m => m.LastName, ""new  
  24.     {  
  25.         @class = "text-danger"  
  26.     }) < /div> < div class = "form-group" > < label > Email < /label>  
  27.     @Html.TextBoxFor(m => m.Email, null, htmlAttributes: new  
  28.     {  
  29.         @class = "form-control"  
  30.     })  
  31.     @Html.ValidationMessageFor(m => m.Email, ""new  
  32.     {  
  33.         @class = "text-danger"  
  34.     }) < /div> < div class = "form-group" > < label > Age < /label>  
  35.     @Html.TextBoxFor(m => m.Age, null, htmlAttributes: new  
  36.     {  
  37.         @class = "form-control"  
  38.     })  
  39.     @Html.ValidationMessageFor(m => m.Age, ""new  
  40.     {  
  41.         @class = "text-danger"  
  42.     }) < /div> < div class = "form-group" > < label > Gender < /label> < div > @Html.RadioButtonFor(m => m.Gender, Model.Gender) < label > Male < /label>  
  43.     @Html.RadioButtonFor(m => m.Gender, Model.Gender) < label > Female < /label>  
  44.     @Html.ValidationMessageFor(m => m.Gender, ""new  
  45.     {  
  46.         @class = "text-danger"  
  47.     }) < /div> < /div> < div class = "form-group" > < input type = "submit"  
  48.     value = "Submit"  
  49.     class = "btn-success" / > < /div>  
  50. }  
HomeController.cs
  1. [HttpPost]  
  2. public ActionResult Index(Employee emp)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         TempData["emp"] = emp;  
  7.         return Redirect("/Home/Details");  
  8.     }  
  9.     else  
  10.     {  
  11.         return View(emp);  
  12.     }  
  13. }  
  14. public ActionResult Details()  
  15. {  
  16.     Employee emp = (Employee) TempData["emp"];  
  17.     return View(emp);  
  18. }  
In the Index ActionMethod with HttpPost we are checking the ModelState.IsValid property.

If ModelState.IsValid is true the form is successfully submitted without any form validation errors, then returning Details view in Home Controller.
If ModelState.IsValid is false then the form is not successfully submitted with form validation error, then returning same view with employee object for repopulating the submitted values and error messages for model object.

Run the Project.

run

Submit the form without providing any values.

form

When form is submitted without any values in this case ModelState.IsValid is false, then returning employee object to index view.

index

age

Up Next
    Ebook Download
    View all
    Learn
    View all