Learn to Apply Validation on Model in MVC

0
1281

MVC-Validation 740X296

Hi all, Today we are going to learn how to apply validation on model.
MVC framework provides us rich support to use data annotation to describe the model for data validation.
We can apply validation on the model class properties. We can use Data Annotation with Data Type Attribute.
In this topic we will learn how to apply validation in model properties and how to use them.

So let’s start with the example

1. Open visual studio and create new project and select MVC web application. Now go to model folder and add new model and name it DemoModels.cs.
1

2

2. Now open DemoModels and paste the below code in it.

Add the namespace System.ComponentModel.DataAnnotations as validation come under System.ComponentModel.DataAnnotations library.

As you can see above I have created properties FirstName, LastName, Email, Age, URL, Phone, UpdateDate.

In this example I have used the validations listed below:

[Required] is used for the required field validation.
[StringLength] define the minimum or maximum length of the string required.
[EmailAddress] is used for the valid email validation.
[Range] is used to apply range validation.
[Phone] is used to validate the phone number.
[URL] is used to validate the valid URL.

You can use DataType which is an enum.

There are lots of validation attributes available. You can use according to your requirement. In this blog, I have implemented few of them.
3

4

Learn HTML5 Programming For Beginners

Now add new strongly typed view and rename it to Demo and select DemoModels from models class.
5

Now paste the below code in demo view

In the above view I have used @Html. TextBoxFor() to bind the model property with the controls. I have also used @Html.ValidationSummary() to see all the validation in a group.
6

Now open Home controller and add the code below in it.

In the above code, you can see that ModelState.IsValid is used. If any of the validation applied on model fails, it return false.
7

Now you are all done. Just run the application and go to Home/Demo and click on submit button and see the result.

8

Summary: In above example, we have learnt how to apply data annotation/ validation in model in MVC.

LEAVE A REPLY

Please enter your comment!
Please enter your name here