Control Validation And User Custom Validation Setting In ASP.NET MVC 4.0

Introduction

Validation means some validation control, it checks the user input data as per your requirements. If the validation is successful, then the data will be processed for further steps, otherwise the data has never been processed for further steps and control will show some warning message to the end user.

Like ASP.NET, we used some validation controls to validate the Server controls, as given below.

RequiredFieldValidator,RangeValidator,CompareValidator,RegularExpressionValidator, CustomValidator,ValidationSummary etc.

Today, I will show you how to implement validation in MVC Controls/ Html Helper Controls.

Step 1

Create one class in Models folder named “Student.cs”

Code Ref

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace val.Models  
  8. {  
  9.     public class Student  
  10.     {  
  11.   
  12.         [Key]  
  13.   
  14.         public int CustomerID { get; set; }  
  15.   
  16.   
  17.   
  18.         [Required(ErrorMessage = "Enter Your Name")]  
  19.         [StringLength(4, ErrorMessage = "Name should be less than or equal to four characters.")]  
  20.         public string Name { get; set; }  
  21.   
  22.   
  23.   
  24.         [Required(ErrorMessage = "Enter Your Address")]  
  25.         [StringLength(10, ErrorMessage = "Address should be less than or equal to ten characters.")]  
  26.         public string Address { get; set; }  
  27.   
  28.   
  29.         [Required(ErrorMessage = "Your must provide a PhoneNumber")]  
  30.         [Display(Name = "Home Phone")]  
  31.         [DataType(DataType.PhoneNumber)]  
  32.         [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]  
  33.         public string Mobileno { get; set; }  
  34.   
  35.   
  36.   
  37.         [DataType(DataType.Date)]  
  38.         [Required(ErrorMessage = "Enter Your DOB.")]  
  39.         [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]  
  40.         [val.Models.UserCustomValidation.ValidBirthDate(ErrorMessage = "Birth Date can not be greater than current date")]  
  41.         public DateTime Birthdate { get; set; }  
  42.   
  43.   
  44.   
  45.         [Required(ErrorMessage = "Enter Your EmailID")]  
  46.         [RegularExpression(@"^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$", ErrorMessage = "Please enter a valid email address")]  
  47.         public string EmailID { get; set; }   
  48.   
  49.   
  50.     }  
  51. }  
Code Description

Here, I declare 6 different entities to access the user and inputs. For every entity, I required an attribute to show the validation message failed for the end users.

e.g. [Required(ErrorMessage = "Enter Your Name")]

Like this required attribute, I used StringLength, Display, DisplayFormat, RegularExpression attributes.

We have used some attributes. For this, we have to add one namespace.
  1. using System.ComponentModel.DataAnnotations;  
You can get the DLL file to access this Namepsace. Inside References folder, we get the screenshot, as shown below.



In name part, I can enter up to 4 characters.

[StringLength(4, ErrorMessage = "Name should be less than or equal to four characters.")]

In address part, I can enter up to 10 characters.

[StringLength(10, ErrorMessage = "Address should be less than or equal to ten characters.")]

In MobileNo. part, I can enter only 10 digit valid phone no.
  1. [DataType(DataType.PhoneNumber)]  
  2. [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]  
In E-mail Id part, I can enter only a valid E-mail Id with @ symbol.
  1. [RegularExpression(@"^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$", ErrorMessage = "Please enter a valid email address")] 
In Date Time part, I can enter only valid date, which should be less than current date.
  1. [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]  
  2. [val.Models.UserCustomValidation.ValidBirthDate(ErrorMessage = "Birth Date can not be greater than current date")]  


Here, I have used one Custom Validation class to customize your Date time Validation. For this, I created one class file in Models folder named “UserCustomValidation.cs” .

Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations; //Here Namespace used for access attributes.  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace val.Models  
  8. {  
  9.     public class UserCustomValidation  
  10.     {  
  11.         [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]  
  12.         public sealed class ValidBirthDate : ValidationAttribute  
  13.         {  
  14.             protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
  15.             {  
  16.                 if (value != null)  
  17.                 {  
  18.                     DateTime _birthJoin = Convert.ToDateTime(value);  
  19.                     if (_birthJoin > DateTime.Now)  
  20.                     {  
  21.                         return new ValidationResult("Birth date can not be greater than current date.");  
  22.                     }  
  23.                 }  
  24.                 return ValidationResult.Success;  
  25.             }  
  26.         }  
  27.     }  
  28. }  
Code Description

Here, I used one date time variable to access date time .
  1. DateTime _birthJoin = Convert.ToDateTime(value);  
Thus, I put some code to take the user’s birth date. Birth date should always be less than today’s date.
  1. if (_birthJoin > DateTime.Now)  
  2.                     {  
  3.                         return new ValidationResult("Birth date can not be greater than current date.");  
  4.                     }  
Here, I used one class,  ValidBirthDate, that is inherited from ValidationAttribute class.
  1. public sealed class ValidBirthDate : ValidationAttribute  
What is ValidationAttribute class?

It serves as a base class for all the validation attributes.

Go to the definition of this ValidationAttribute class.



Here, the System.ComponentModel.DataAnnotations.dll file references for this class files.
  1. #region Assembly System.ComponentModel.DataAnnotations.dll, v4.0.0.0  
  2. // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.ComponentModel.DataAnnotations.dll  
  3. #endregion  
The ValidationResult override method is used to represent a container for the result of the validation request. The ValidationContext class acts as a parameter inside ValidationResult override method. It is used for describing a context in which validation check is performed. 
  1. protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
  2. return new ValidationResult("Birth date can not be greater than current date.");  
  3. return ValidationResult.Success;  

 
In custom validation class, I used Student.cs for DATE TIME entity . According to this, the user input date should be less than today’s date.
  1. [val.Models.UserCustomValidation.ValidBirthDate(ErrorMessage = "Birth Date can not be greater than current date")]  
Here, UserCustomValidation is the name of the Model Class and ValidBirthDate class is the child class of ValidateAttribute base class.

Step 2

Here, I create one controller class file named “StudentController.cs”

Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using val.Models;  
  7.   
  8. namespace val.Controllers  
  9. {  
  10.     public class StudentController : Controller  
  11.     {  
  12.           
  13.   
  14.         [HttpGet]  
  15.         public ActionResult Index()  
  16.         {  
  17.               
  18.   
  19.             return View();  
  20.   
  21.         }  
  22.   
  23.         [HttpPost]  
  24.         public ActionResult Index(Student model)  
  25.         {  
  26.              
  27.   
  28.             return View();  
  29.   
  30.   
  31.   
  32.         }  
  33.   
  34.     }  
  35. }  
Code Description

Here, I used namespace, using val.Models;

Due to all the related entities, we can access any related properties by assigning the class file inside controller action method.
  1. [HttpPost]  
  2.         public ActionResult Index(Student model)  
  3.         {  
  4.             return View();  
  5.   
  6.         }  
Here, Index is the Controller Action Method and Student is the model class file inside Models folder.



Step 3

Here, I created one Chtml file for view to EndUser named “Index.cshtml”.

Code Ref
  1. @model val.Models.Student  
  2.   
  3. @{  
  4.   
  5.     Layout = null;  
  6.   
  7. }  
  8.   
  9. <!DOCTYPE html>  
  10.   
  11. <html>  
  12.   
  13. <head>  
  14.   
  15.     <meta name="viewport" content="width=device-width" />  
  16.   
  17.     <title>Student Insert</title>  
  18.   
  19. </head>  
  20.   
  21. <body>  
  22.   
  23.     <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  24.   
  25.     <script src="~/Scripts/jquery.validate.min.js"></script>  
  26.   
  27.     <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
  28.   
  29.     <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />   
  30.   
  31.     @using (Html.BeginForm())  
  32.     {  
  33.   
  34.         @Html.ValidationSummary(true)  
  35.   
  36.         <fieldset>  
  37.   
  38.             <legend style="font-family:Arial Black;color:Green">Student Details</legend>  
  39.   
  40.             <div class="editor-label" style="font-family:Arial Black">  
  41.   
  42.                 @Html.LabelFor(model => model.Name)  
  43.   
  44.             </div>  
  45.   
  46.             <div class="editor-field" style="color:Red;font-family:Arial">  
  47.   
  48.                 @Html.EditorFor(model => model.Name)  
  49.   
  50.                 @Html.ValidationMessageFor(model => model.Name, "*")  
  51.   
  52.             </div>  
  53.             <div class="editor-label" style="font-family:Arial Black">  
  54.   
  55.                 @Html.LabelFor(model => model.Address)  
  56.   
  57.             </div>  
  58.   
  59.             <div class="editor-field" style="color:Red;font-family:Arial">  
  60.   
  61.                 @Html.EditorFor(model => model.Address)  
  62.   
  63.                 @Html.ValidationMessageFor(model => model.Address, "*")  
  64.   
  65.             </div>  
  66.   
  67.             <div class="editor-label" style="font-family:Arial Black">  
  68.   
  69.                 @Html.LabelFor(model => model.Mobileno)  
  70.   
  71.             </div>  
  72.   
  73.             <div class="editor-field" style="color:Red;font-family:Arial">  
  74.   
  75.                 @Html.EditorFor(model => model.Mobileno)  
  76.   
  77.                 @Html.ValidationMessageFor(model => model.Mobileno, "*")  
  78.   
  79.             </div>  
  80.   
  81.             <div class="editor-label" style="font-family:Arial Black">  
  82.   
  83.                 @Html.LabelFor(model => model.Birthdate)  
  84.   
  85.             </div>  
  86.   
  87.             <div class="editor-field" style="color:Red;font-family:Arial">  
  88.   
  89.                 @Html.EditorFor(model => model.Birthdate)  
  90.   
  91.                 @Html.ValidationMessageFor(model => model.Birthdate, "*")  
  92.   
  93.             </div>  
  94.   
  95.             <div class="editor-label" style="font-family:Arial Black">  
  96.   
  97.                 @Html.LabelFor(model => model.EmailID)  
  98.   
  99.             </div>  
  100.   
  101.             <div class="editor-field" style="color:Red;font-family:Arial">  
  102.   
  103.                 @Html.EditorFor(model => model.EmailID)  
  104.   
  105.                 @Html.ValidationMessageFor(model => model.EmailID, "*")  
  106.   
  107.             </div>  
  108.   
  109.             <p>  
  110.                 <input type="submit" value="Insert" style="color:Navy;font-family:Arial; font-size:large" />  
  111.                 <input type="reset" value="Reset" style="color:Navy;font-family:Arial; font-size:large" />  
  112.             </p>  
  113.   
  114.             @Html.ValidationSummary(false"Please Check Your Inputs And Try Again !")  
  115.   
  116.         </fieldset>  
  117.   
  118.     }  
  119.   
  120. </body>  
  121. </html>  


Code Description

Here, I have added Model Class Reference Student in cshtml file.
  1. @model val.Models.Student  
We need to add some script file and style sheet to customize validation style formats.
  1. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  2. <script src="~/Scripts/jquery.validate.min.js"></script>  
  3. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
  4. <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
Here Site.css takes an important role to show validation message to the end user in a  format and color like this.

Inside Content folder, the “Site.css” file is there.

Code Ref
  1. body {  
  2.     font-size: .85em;  
  3.     font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;  
  4.     color: #232323;  
  5.     background-color: #fff;  
  6. }  
  7.   
  8. header, footer, nav, section {  
  9.     display: block;  
  10. }  
  11.   
  12.   
  13. /* Styles for basic forms 
  14. -----------------------------------------------------------*/  
  15. fieldset {  
  16.     border: 1px solid #ddd;  
  17.     padding: 0 1.4em 1.4em 1.4em;  
  18.     margin: 0 0 1.5em 0;  
  19. }  
  20.   
  21. legend {  
  22.     font-size: 1.2em;  
  23.     font-weight: bold;  
  24. }  
  25.   
  26. textarea {  
  27.     min-height: 75px;  
  28. }  
  29.   
  30. .editor-label {  
  31.     margin: 1em 0 0 0;  
  32. }  
  33.   
  34. .editor-field {  
  35.     margin: 0.5em 0 0 0;  
  36. }  
  37.   
  38.   
  39. /* Styles for validation helpers 
  40. -----------------------------------------------------------*/  
  41. .field-validation-error {  
  42.     color: #f00;  
  43. }  
  44.   
  45. .field-validation-valid {  
  46.     display: none;  
  47. }  
  48.   
  49. .input-validation-error {  
  50.     border: 4px solid #f00;  
  51.     background-color: #fee;  
  52. }  
  53.   
  54. .validation-summary-errors {  
  55.     font-weight: bold;  
  56.     color: #f00;  
  57. }  
  58.   
  59. .validation-summary-valid {  
  60.     display: none;  
  61. }  
Code Description

The .field-validation-error, .field-validation-valid, .input-validation-error, .validation-summary-errors, .validation-summary-valid CSS class files are important for making validation messages with eye catching formats.

As per your requirement, you can customize your validation summary style formats here.
  1. /* Styles for validation helpers 
  2. -----------------------------------------------------------*/  
  3. .field-validation-error {  
  4.     color: #f00;  
  5. }  
  6.   
  7. .field-validation-valid {  
  8.     display: none;  
  9. }  
  10.   
  11. .input-validation-error {  
  12.     border: 4px solid #f00;  
  13.     background-color: #fee;  
  14. }  
  15.   
  16. .validation-summary-errors {  
  17.     font-weight: bold;  
  18.     color: #f00;  
  19. }  
  20.   
  21. .validation-summary-valid {  
  22.     display: none;  


Here, I put the code for validation summary.

@Html.ValidationSummary(true)


Now, every entity in student class file is assigned, as shown below to make the validation messages, if the input by the user fails or empty.

@Html.LabelFor(model => model.Name)

Here, I will use label heading for this entity.

@Html.EditorFor(model => model.Name)

Here, I use Editor control for this entity.

@Html.ValidationMessageFor(model => model.Name, "*")

Here, I need to use validation message which will be shown for this entity. Here, I used asterisk symbol which will be shown on the right hand side of control validation. Like above mentioned control, I used the same method for other controls for validation purposes. Subsequently, I used Submit and Reset button

If validation fails, then the control validation message will be shown to the end user after clicking submit button.
  1. <input type="submit" value="Insert" style="color:Navy;font-family:Arial; font-size:large" />  
With the help of the reset button, you can reset the Inputs inside the control or make empty control inputs by clicking the reset button.
  1. <input type="reset" value="Reset" style="color:Navy;font-family:Arial; font-size:large" />  
The most important thing that I used is validation summary control with main heading about validation along with individual validation messages of the individual MVC controls.

@Html.ValidationSummary(false, "Please Check Your Inputs And Try Again !")

Step 4

Here, I need to mention Start page in RouteConfig.cs file.

Code Ref
  1. defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }  
Output



The URL is - http://localhost:50926/Student/Index

See all design entities are shown, as mentioned In Views. Without putting in any data, if we click Submit button, then validation message will come. Please check your inputs and try again.
  • Enter your Name
  • Enter your Address
  • You must provide a PhoneNumber
  • Enter your DOB.
  • Enter your E-mail ID


The asterisks are shown with Red highlighted control in the right hand side.



Now, check for custom validations. For this, we have to put some data.

When I put some invalid data, it will not satisfy the conditions in Student.Cs file, then a different validation message will show.

Please check your inputs and try again.
  • Name should be less than or equal to four characters.
  • Address should be less than or equal to ten characters.
  • Not a valid Phone number.
  • Birth date can not be greater than the current date.
  • Please enter a valid email address.


See that the above mentioned controls are shown with an invalid input data with red highlighted mark with asterisk and validation summary message which is shown below the controls with a red mark.

Now, we need to check for the valid data and the  satisfied condition in Student.cs file. Hence, no validation message appears.



Here is the output for the selected controls validation message instead of ALL. I entered Invalid data for Home Phone , Birth Date and Email ID, so validation message will appear as shown below. 

Please check your inputs and try again
  • Not a valid Phone number.
  • Birth date can not be greater than the current date.
  • Please enter a valid email address.



Before clicking Insert button, we can test it for Reset button.

Before clicking Reset button, I entered some records.



After clicking on Reset button, all control values are blank.



Based on this process and method, we can implement validation message and validation summary message as well as customize validation messages.

Summary
  1. How to set for validation message, if controls are blank.
  2. How to set for validation message, if controls have the invalid value.
  3. How to customize validation message and validation summary messages, as per client requirements.
  4. How to set CSS and scripting file to customize the style format of validation message and validation summary message. 

Up Next
    Ebook Download
    View all
    Learn
    View all