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:
- Server side Validations
- 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.
- Using ModelState Object
- Using Data Annotation
- Using Jquery
- 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 |
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
View
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 "mrpachbhai@gmail.com". 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.
References
MSDN
Points of Interest
Comments and suggestions are most welcome.