MVC has a great option to provide a validation with attributes in System.ComponentModel.DataAnnotations. There’s a great tutorial on ASP.NET MVC homepage. MVC 3 brings something new under the table. In previous version we could use few default attributes (or write our own). For example, Required, RegularExpression, StringLength, etc. With new version we can use compare attribute. Lets see this in a example.
Scenario:
We want to provide a validation in our registration form. The password must be the same. For simplicity, I’ll use a simple example.
public class UserReg
{
[Required]
[StringLength(10)]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string ComparePassword { get; set; }
}
Our user interface looks like this (after calling it from the controller):

The problem is, that we must provide a way to compare field Password and ComparePassword to provide accurate information for our system. The easiest way to do that is to provide a Compare attribute.
public class UserReg
{
[Required]
[StringLength(10)]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
[Compare("Password",ErrorMessage = "Provide the same password as in Password field")]
public string ComparePassword { get; set; }
}
And the result:

If we want to provide a hint (and we are using LabelFor helpers), we can pass the optional string to show our text (not the default one):
<div class="editor-label">
@Html.LabelFor(model => model.ComparePassword,"Enter same password as upper")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ComparePassword)
@Html.ValidationMessageFor(model => model.ComparePassword)
</div>
And the result is a little bit better:

We can improve this even further (we can use globalization in our error messages etc.), but that’s for another topic.