Compare Data Annotation attribute in MVC3 Razor

  1. The compare attribute ensures two properties on a model object have the same value.
  2. This attribute is usually used to compare email address or passwords.
  3. This attribute is in System.Web.Mvc namespace. In order to use this attribute, we need to include this namespace.

Example 1 :

In the above example, we have applied Compare attribute to ConfirmPassword property, which compares it with Password property. This attribute ensures same value for both the properties, and displays error message in other case. 

UI :

We gave ConfirmPassword value different from Password value, which resulted in validation failure and error message is shown on UI. The error message is the default one, we have not specified any error message in above example.

Example 2 :

In the above example, we have also specified the error message to display on UI when validation fails.

Example 3 :

In the above example, we are picking error message from resource files. The above code expects a resource file with name Multi.resx having key with name ConfirmPassword_Message which holds the error message.

Resource :

UI :

When validation fails, system picks the error message from resource file.

Watch Video :


Post a Comment