Model Validation in ASP.NET MVC

In web applications, domain validation plays a core part. Data entered from the client’s end may not always be correct. Therefore you need to ensure that the data entered by the client is not only validated but is also correct application-logic wise.

This article is about the ASP.NET Model validations. The following three type of validations we can do in ASP.NET MVC web applications:

  1. HTML validation / JavaScript validation
  2. ASP.NET MVC Model validation
  3. Database validation

But the most secure validation is the ASP.NET MVC model validation. In HTML/JavaScript, the validation can break easily, but the model validation can't. In ASP.NET MVC model validations are done using Data Annotation, its inherited System.ComponentModel.DataAnnotations assembly. In ASP.NET MVC 4 provides a different way to build custom validation.

Before you do the ASP.NET MVC model validations you need to add the following reference:

using System.ComponentModel.DataAnnotations;

Now you are ready to do the model validations.

In the example, create a new class called “company” under the Model add the preceding references:

namespace

Now add the properties. In the following example, I have added various properties that are not directly related to the “company.”

company

add the properties

  1. [Display(Name = "Company Id")]  
  2. public int CompanyRegisterId { getset; }   
In the preceding example you need to only add the “Required” attribute without using an error message. The default message will appear as in the following:

Required
  1. [Display(Name = "Company Id")]  
  2. [Required (ErrorMessage= "Company Id is Required")]  
  3. public int CompanyRegisterId { getset; }   
But if you add an error message then a custom error message will appear as in the following:

id

In HTML view you do not even need to add a label. Using ASP.NET.MVC Model we can do that easily.

The only thing is, you need to call the relevant attribute in the HTML view using Razor syntax.

The “ComponentModel.DataAnnotations” assembly has many built-in validation attributes, for example:
  • Required
  • Range,
  • RegularExpression ,
  • Compare
  • StringLength
  • Data type

There are many data types the user can select to validate the input. Using this, you can validate for the exact data type as in the following:

  • Credit Card number
  • Currency
  • Custom
  • Date
  • DateTime
  • Duration
  • Email Address
  • HTML
  • Image URL
  • Multiline text
  • Password
  • Phone number
  • Postal Code
  • Text
  • Tine
  • Upload
  1. [Required (ErrorMessage="Company Email address Required")]  
  2. [DataType(DataType.EmailAddress)]  
  3. public string CompanyEmailAddress { getset; }

  4. [Required (ErrorMessage="Company Phone number is Required")]  
  5. [DataType(DataType.PhoneNumber)]  
  6. public int CompanyPhoneNumber { getset; }  

  7. [Range (1,100)]  
  8. [DataType (DataType.Currency)]  
  9. public Decimal MinimumSalaryPerEmp { getset; }  
  10.   
  11. [Required]  
  12. [DataType (DataType.MultilineText)]  
  13. public string CompanyDescription { getset; }  
  14.   
  15. [Required]  
  16. [DataType (DataType.PostalCode , ErrorMessage = " Please Enter Valid Postal Code")]  
  17. public String PostalCode { getset; }  
Also, you can validate the range as in the following examples. The minimum value you can enter here is 2, whereas the maximum value you can enter is 10.
  1. [Required (ErrorMessage="No.of working Hours Required")]  
  2. [Range(2, 10, ErrorMessage = "Please Provide correct range. It should be minimum 2 and not more than 10 ")]  
  3. public int WorkingHours { getset; }  
Also you can validate the string length using model validation.
  1. [Required]  
  2. [StringLength (10 , MinimumLength =5)]  
  3. [Display(Name = "User name")]  
  4. [RegularExpression (@"(\S\D)+", ErrorMessage =" Space and numbers not allowed")]  
  5. public string UserName { getset; }  
In the preceding, you cannot exceed 10 letters, although it should be a minimum of 5 letters. It is also important that a regular expressions be used to do some validations. Using regular expressions I ignore empty spaces and digits that the user may enter in the text box.

You can compare a user-entered password and re-enter password that are matched using this compare attribute.
  1. [Required]  
  2. [DataType (DataType.Password)]  
  3. [Display (Name = "Enter Password")]  
  4. public string CurrentPassword { getset; }  
  5.   
  6. [Required]  
  7. [Display (Name = "Re-enter Password")]  
  8. [Compare("CurrentPassword" , ErrorMessage = "Please Re-enter Password Again")]  
  9. public string ComparedPassword { getset; }  
Using “DisplayFormat” you can specify the data format that should be displayed. For example, display date, currency, etc.
  1. [Display(Name = "Company Founder Name")]  
  2. [DisplayFormat(NullDisplayText = "anonymous")]  
  3. public string CompanyFounder { getset; }  
Here, instead of displaying null, you can display anonymous.

Now create a controller and a view to apply those validations. In this example I am using a default controller and view. The Index action returns a view that contains a form through that a user can fill in the details of the company and submit it.

Sometimes a user needs to implement validation scenarios that are not provided in the MVC framework.

In these kinds of scenarios you need to implement an “IValidatableObject” interface. Using this, you can conduct an in-depth inspection of the model.
  1. public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)  
  2. {  
  3.    if (MinimumSalaryPerEmp < 10 && WorkingHours > 5)   
  4.    {  
  5.       yield return new ValidationResult("Provide Fair Amount for Workers");  
  6.    }  
  7. }  
In the preceding example, the method used will allow you to access all the properties in the model and you can easily implement the custom validation logic also.

(Important: in the view “ValidationSummary” needs to be true.)
  1. @Html.ValidationSummary(true))  
When the user submits the form view, the controller will send a POST request. To respond to this request, we need to create one more ActionResult in our controller.
  1. [HttpPost]  
  2. public ActionResult Index(Company company)  
  3. {  
  4.    if (ModelState.IsValid)  
  5.    {  
  6.       // TO DO  
  7.       return View();  
  8.    }  
  9.    return View();  
  10. }  
Considering the view, you may first need to add the model reference as in the following:
  1. @model SampleModelValidation.Models.Company  
Thereafter you add the form inputs and validation that you implemented in the model. It is important that the form inputs should be inside the BeginForm as shown below:

code

inside the BeginForm

BeginForm

Now your web application will be ready to run. Run the website, if incorrect input values are submitted you will then see invalid input error messages.

This validation only applies to the server side. But there is also a need to do validation from the client side as well. When considering client-side validation, reducing the server load will be a great benefit to the user. The ASP.NET MVC Framework will support client-side validations as well.

To do client-side validation, a few JavaScripts can be used. They are:
  1. jQuery
  2. jQuery validation library
  3. jQuery unobtrusive validation library (developed by Microsoft)

When you open a new ASP.NET.MVC project you will get all the JavaScripts in the scripts folder that you want in the client-side validation. First we should set the configuration inside the <appSettings> tag in the web.config file.

appSettings

Now we need to add the JavaScript references inside the “BundleConfig.cs” file, creating a new script bundle as shown below.

BundleConfig

Then render these scripts in the “_Layout.chtml” file as shown below.

  1. @Scripts.Render("~/bundles/jqueryval")  
Now you are good to go with client-side validation and server-side validation as well.

validation

 


Similar Articles