Click here to Skip to main content
13,861,991 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


67 bookmarked
Posted 7 Oct 2015
Licenced CPOL

Validations in MVC

, 7 Oct 2015
Rate this:
Please Sign up or sign in to vote.
Validations in MVC


Why Validations?

For any website, there are many input fields. Users enter the data in those input fields. Now the input fields are exposed to the client browser. Users can enter anything they wants to the input fields. If the user enters some wrong data then we will have some irrelevant or wrong data with us in the database also. In this way, providing the authority to user to enter data in input fields which we will be inserting into the database and which will be used for many purposes may cause security holes in to the system if we don't put any restrictions on the input fields.

Here's where validations comes into the picture. Validations play an important role in the success of any website.

What are Validations?

In simple language we can say that validations are some rules set by the developer on input fields so as to satisfy the business rules for that particular input field in order to have the proper data in the system.

There are two types of validations:

  1. Server side Validations
  2. Client Side Validations

While performing validations we need to take care of not only the proper validation, but also ensure the validation meets the business rule as per the requirement. From a security perspective, it is often possible that some hackers may bypass client side validation and insert some vulnarable data to server.


Different platforms have different ways of providing facility of validations. ASP.NET has validation controls with the help of which we can achieve the validations at server side. On client side we can achieve validations using JavaScript/jQuery. Nowadays there are many plugins which are used to carry out the client side validations. MVC framework supports server side and client side validations with inbuilt features. In MVC, validations have evolved since MVC 2. In MVC 2, there was support for Data annotations but MVC 3 introduced enhancements in Data Annotations for validations on server side and client side, as well as remote validations and compare attribute are added in MVC 3.0.

We will see the validations in MVC.Validations can be performed using the below methods.

  1. Using ModelState Object
  2. Using Data Annotation
  3. Using Jquery
  4. Custom validations can be applied to input fields using classes of MVC framework.


Server side Validations

I have created an MVC project with name MVCValidation with a Basic template. For this template, I have created one model Register.cs Let us look into Register.cs.

Making use of this model I will explain the basic server side validation. Framework Validates all the fields of the model using ModelState object. In code we need to check the IsValid property of the ModelState object. If there is a validation error in any of the input fields then the IsValid property is set to false. If all the fields are satisfied then the IsValid property is set to true. Depending upon the value of the property, we need to write the code. The MVC framework provides the feature of data annotations for validations. Data Annotation does all the above mentioned validations automatically and we need to only check the IsValid property.

I will first explain this server side validation without using data annotation attribute and using the ModelState Object.

Using ModelState Object

I have created one view Register.cshtml with strongly typed model Register.cs

The Register view of the application will look like below

Now I will create one HTTPPOST method that will get hit once I click on the Submit button on Register view.

In this Register view, we will check whether the input properties in the model i.e UserName, Password and ConfirmPassword are Null/Empty. If those fields are Null/Empty then we will add error in ModelState object against that respective property.

Please find below the image with code

If I run the application and try to submit the register form with all the fields empty, then in the controller method, register model will get null values assigned to all the properties.

At the end of the execution ModelState Object will contain all the errors which are added for failed validation. Also the modelState object will contain the error message.

As we are checking the value of IsValid property and it gets set to false, so we are redirecting the user to the register view again to fill up the fields.

The view will look like the below with error messages.

So this is a server side validation which is carried out without use of the data annotation attribute. We will see how data annotation makes the life of a developer very easy.

Data Annotation Attributes

Please find below some of the data Annotation attribute and its use. Please note that references are taken from MSDN.

Attribute Name Use

This attribute specifies the type of the property like emailId OR phoneNumber.


public string Email { get; set; }



Specifies the maximum and minimum value for property.


public int Age { get; set; }



Specifies the valid value for property.


      ErrorMessage="Please enter valid email id.")]
public string EmailId { get; set; }



Specifies that value of the property must be provided


[Required(ErrorMessage="Please enter First Name")]
public string FirstName { get; set; }



Specifies how many number of characters are allowed for that particular property.NULL value will not fire StringLength validation for that particular property.


public string FirstName { get; set; }



This attribute is used to enhance the current property for which the attribute needs to be applied.


[Display(Name = "First Name", Description="First Name of the person")]
public string FirstName { get; set; }



This attribute is used to specify how the fields should be displayed and formatted


[DisplayFormat(DataFormatString = "{0:C}")]
  public Decimal ListPrice { get; set; }


Using Code

In our code we will increase some properties in model and view that will explian use of these properties.

Please fine below the Model, View and the result after validation.



Result of Validation

Custom Server Side Validations

Sometimes we need to create custom validations by creating custom Attributes. Consider, for example, we want to set a lower limit for the salary of the employee. I will create one custom validation attribute. In order to create a custom validation attribute, we need to create one class which is derived from ValidationAttribute class. There is one function in ValidationAttribute class which performs the validation part. In the attribute class, we have to override the IsValid function and all the custom validation logic should go inside this IsValid function. Let us name the attribute as SalaryAttribute.

If I enter all the fields and enter the salary value as 10000 and click on submit button then the Salary attribute will validate the salary field and will give server side error.

If the salary value is entered as 60000 and clicked on submit button then the form will be submitted successfully. All the validations are passed and the user will be redirected to the index view.

In this way we have implemented custom server side validation.

Remote Validation

Remote validation is one important and useful feature provided by MVC. This feature allows the user to call any action method of the controller from client side. For example, suppose we need to check whether the email id of the user exists in the database, and when the user types his email id in Email field and clicks outside of email id text field. Here if we use a remote validator then a call to the action method can be fired and the email id is checked for existance. If the email id exists, then a proper error message can be returned to the UI immediately. We need not to wait for Submit button click.

So remote validation works like AJAX call. We need to include the below files in cshtml in order to trigger the call on tab out of email field.

<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>

The Remote Validation attribute will get added to email property.

The action method will check if the email id entered is equal to "". If it is equal then error message will be returned to UI.

UI will immediately display an error message on tab out

In this way we are done with remote validation.

Client side Validation

Client side validations are very useful when we think of performance perspective. Whenever any user places any wrong data at that time, we need to go to server side and validation occurs at server side. So we can reduce this call from client to server if we do validations at client side. Ultimately our performance will get increased.

Also with client side validations, we are providing the ability to the user for a correction in data before we send it to server. But if we have client side validations, then what is needed for server side validation? Some browsers OR some clients do not support client side scripting at that time we need server side validations to validate our data before storing it in the database. MVC provides the feature of UnObstrusive client side validation.

How to enable client side validation in MVC?

In order to enable client side validation in mvc, you need to follow below steps.

You need to include below files in the view.

If you want to use bundling then you need to add the js files in bundle.

Validation is carried out using the jQuery Validation library. Generally, in webform based applications, we make use of JavaScript in order to do client side validations. In MVC, client side validation do not introduce any JavaScript in the code to carry out validation. Please see the below structure of HTML after enabling client side validation.

HTML: Before Enabling Client side validation

HTML: After enabling client side validation

Now for each input field for which the validation attribute is added in Model, the above structure is created by framework. The data-val attribute is set to true and the attribute data-val-{Name} is added as per the attribute added in model. In this example, we have added the Required attribute so the name becomes data-val-required. The error message gets assigned to the data-val-attribute.

Please note that the input field which needs to be validated at client side should be placed inside of the html form tag to get validated by validation js.

Custom Client Side Validation

In our model, "Register.cs," we have created a server side custom validation for the Salary field. This validation will get fired only at the server side. Now we will create one custom client side validation that will get fired as soon as the user enters some value in the salary field and the user will receive the error message immediately.

For this purpose I have created one JavaScript file "CustomValidation.js". The file will contain one validation rule-"checkSalary". This newly added rule is applied against the Salary field of the form. This is mentioned in the .Validate method as well as an error message is set up in the function. Please see the below image which will describe all the parts of the js code.

Now we need to include the script in our cshtml. Once we execute the application and after entering the salary as 10000, see the execution. We are returning false if validation fails and true if validation passes.

In this case the client side validation fails for salary field and below error message is immediately displayed to use.

In this way, we have seen both the server side validation and client side validation in MVC. Comments and suggestions are most welcome.



Points of Interest

Comments and suggestions are most welcome.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mahesh Pachbhai
Software Developer
India India
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionComplete Solution for MVC Validations Pin
Vikas Thombre18-Dec-17 23:26
memberVikas Thombre18-Dec-17 23:26 
PraiseMessage Closed Pin
31-Aug-17 2:36
memberer.vks31-Aug-17 2:36 
GeneralMy vote of 5 Pin
Prasad_Kulkarni16-Jul-17 23:39
memberPrasad_Kulkarni16-Jul-17 23:39 
GeneralMy vote of 5 Pin
Cipherc14-Jul-17 3:31
memberCipherc14-Jul-17 3:31 
PraiseGood Work... Pin
HiiMeSH7-Apr-17 4:35
memberHiiMeSH7-Apr-17 4:35 
PraiseMy vote of 4 Pin
Bhuban _Shrestha31-Jan-17 3:12
professionalBhuban _Shrestha31-Jan-17 3:12 
QuestionWhy does ASP.NET MVC client side validation not use the HTML5 constraint validation API? Pin
Gerd Wagner28-Nov-15 10:55
professionalGerd Wagner28-Nov-15 10:55 
PraiseVery good article Pin
Stumangr23-Oct-15 3:43
memberStumangr23-Oct-15 3:43 
GeneralMy vote of 5 Pin
Gaston Verelst20-Oct-15 21:47
memberGaston Verelst20-Oct-15 21:47 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun20-Oct-15 2:50
memberHumayun Kabir Mamun20-Oct-15 2:50 
QuestionGood Article Pin
Anushree Partani8-Oct-15 21:42
memberAnushree Partani8-Oct-15 21:42 
QuestionGood Article Pin
Santhakumar M8-Oct-15 5:13
professionalSanthakumar M8-Oct-15 5:13 
QuestionNice article Pin
Ram Nunna7-Oct-15 22:33
professionalRam Nunna7-Oct-15 22:33 
QuestionGreat article Pin
Stu Hamm7-Oct-15 7:50
memberStu Hamm7-Oct-15 7:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190214.1 | Last Updated 7 Oct 2015
Article Copyright 2015 by Mahesh Pachbhai
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid