Click here to Skip to main content
15,881,204 members
Articles / Programming Languages / C#

Validations in MVC

Rate me:
Please Sign up or sign in to vote.
4.74/5 (51 votes)
7 Oct 2015CPOL9 min read 153.9K   68   17
Validations in MVC

Introduction

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.

Background

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.

Image 1

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

Image 2

The Register view of the application will look like below

Image 3

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

Image 4

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.

Image 5

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.

Image 6

Image 7

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.

Image 8

The view will look like the below with error messages.

Image 9

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
DataType

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

Ex:

[DataType(DataType.EmailAddress)]
public string Email { get; set; }

 

Range

Specifies the maximum and minimum value for property.

Ex:

[Range(1,100)]
public int Age { get; set; }

 

RegularExpression

Specifies the valid value for property.

Ex:

[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", 
      ErrorMessage="Please enter valid email id.")]
public string EmailId { get; set; }

 

Required

Specifies that value of the property must be provided

Ex:

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

 

StringLength

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

Ex:

[StringLength(50)]
public string FirstName { get; set; }

 

Display

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

Ex:

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

 

DisplayFormat

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

Ex:

[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.

Model

Image 10

View

Image 11

Result of Validation

Image 12

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.

Image 13

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.

Image 14

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.

Image 15 Image 16

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.

Image 17

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

Image 18

UI will immediately display an error message on tab out

Image 19

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.

Image 20

You need to include below files in the view.

Image 21

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

Image 22

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

Image 23

HTML: After enabling client side validation

Image 24

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.

Image 25

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.

Image 26

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

Image 27

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

References

MSDN

Points of Interest

Comments and suggestions are most welcome.

License

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


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionA question Pin
Member 1475654126-Feb-20 15:18
Member 1475654126-Feb-20 15:18 
QuestionCustom Validations Pin
Member 1452957113-Jul-19 7:12
Member 1452957113-Jul-19 7:12 
QuestionComplete Solution for MVC Validations Pin
Vikas Thombre18-Dec-17 22:26
Vikas Thombre18-Dec-17 22:26 
GeneralMy vote of 5 Pin
Prasad_Kulkarni16-Jul-17 22:39
Prasad_Kulkarni16-Jul-17 22:39 
GeneralMy vote of 5 Pin
Cipherc14-Jul-17 2:31
Cipherc14-Jul-17 2:31 
PraiseGood Work... Pin
HiiMeSH7-Apr-17 3:35
HiiMeSH7-Apr-17 3:35 
PraiseMy vote of 4 Pin
Bhuban _Shrestha31-Jan-17 2:12
professionalBhuban _Shrestha31-Jan-17 2:12 
QuestionWhy does ASP.NET MVC client side validation not use the HTML5 constraint validation API? Pin
Gerd Wagner28-Nov-15 9:55
professionalGerd Wagner28-Nov-15 9:55 
PraiseVery good article Pin
Stumangr23-Oct-15 2:43
Stumangr23-Oct-15 2:43 
GeneralMy vote of 5 Pin
Gaston Verelst20-Oct-15 20:47
Gaston Verelst20-Oct-15 20:47 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun20-Oct-15 1:50
Humayun Kabir Mamun20-Oct-15 1:50 
QuestionGood Article Pin
Anushree Partani8-Oct-15 20:42
Anushree Partani8-Oct-15 20:42 
QuestionGood Article Pin
Santhakumar M8-Oct-15 4:13
professionalSanthakumar M8-Oct-15 4:13 
QuestionNice article Pin
Ram Nunna7-Oct-15 21:33
professionalRam Nunna7-Oct-15 21:33 
QuestionGreat article Pin
Stu Hamm7-Oct-15 6:50
Stu Hamm7-Oct-15 6: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.