Asp.Net MVC data annotations compare attribute with example

In this tutorial i am going to explain about Asp.Net MVC data annotations compare attribute with example. In my previous tutorial i have explained about

Implementation :

Now we will see the implementation of Asp.Net MVC data annotations compare attribute with example. Before going into detail,let me explain what is compare validation attribute and the use of compare validation attribute. Compare validation attribute – from its name itself we can identify that it is used to compare two or more fields.

It is mainly useful when we have the validation in form like we need to confirm the entered values like confirming the emaiaddress,password or in case banking transaction before doing transaction it may ask you to reenter the account number. It adds one more level of security so that manual typing error doesn’t cause any problem.

Now lets see how we can do it in our application. First open visual studio and create a new mvc project. Once the project is added right click on the model folder and add a model Called UserModel. Open the created model and add the below code.

If you check the above code i have password and confirm password properties in my model. And ConfirmPassword property is decorated with Compare attribute. It means ConfirmPassword value will be compared with Password property value. If it matches then it consider it as valid else it will display the error as Password and confirm password doesn’t match. 

Now right click on controller folder and add new empty mvc folder. If you open the generated file and add the below code. Since i am explaining about compare attribute i didn’t write any code inside my action method.

Now right click on the CreateUser action method and choose AddView. Follow the steps and add view to CreateUser action method using Create template and UserModel model class.  The generated view will look like below.

Below is my layout file.


Now if you run the program you can see the output of Asp.Net MVC data annotations compare attribute with example. So if you enter the same value in password and confirm password textbox then it won’t throw any error else it will throw the error. Refer the below screenshot.

Output of Asp.Net MVC dataannotations compare attribute with example


Hope you learned Asp.Net MVC data annotations compare attribute with example. Do you like this tutorial? Help us to improve. Please post your comments and feedback below.

Leave a Reply

Your email address will not be published. Required fields are marked *