Data Haunting

Easy Solutions Destination

By

Client and Server side Validation using DataAnnotation in MVC

In this article we will see how to validate Asp.net MVC form using client and server side validation using Data Anotataion. Here we will use DataAnnotation’s different attribute like Required, RegularExpression, EmailAddress, StringLength, Range, MinLength, MaxLength, DataType.EmailAddress, DataType.Password etc.

Client and Server side validation in MVC
Suppose our form validation is as per above snap So now we will create Strongly type Model, View and Controller as per our requirements.

Create Model

While creating model using DataAnnotation you must include namespace using System.ComponentModel.DataAnnotations. Now our model would be like below.

Above we have used different DataAnnotation’s attribute for validation like Required, EmailAddress, StringLength, Compare, Range and DataType.EmailAddress and DataType.Password.

Create Strongly Typed View

Before going to designing view, here we also implementing client side validation using DataAnnotations in MVC, we must be ensure that in our web.config file “ClientValidationEnabled” and “UnobtrusiveJavaScriptEnabled” must be true.

and also be ensure that you have added all required jquery properly without any conflict as shown below.

Now our view will be strongly typed with our model as per below code so all the Model property can apply to our View.

Create Controller

Now we will create our Controller’s Action. We have design one Get Method for default loading data in View and one Post method for passing Data from View to Controller.

Above in Post method we have put one condition that is ModelState.IsValid which checked our Server side validation. Suppose our server side validation is not full fill than it will goes to else condition and than will render it’s specific view with all error message. So you can check as per above code for Server side validation using ModelState.IsValid or not ?

What is your opinion ?

Here we have seen how to apply client side and server side validation in asp.net mvc using Data Annotation. I hope it will be very useful for validation in MVC . If you have any query you can comment or you can mail me.

Leave a Reply