MVC notes – validation compare attribute

by Bojan Vrhovnik 10. February 2011 15:31

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):

image

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:

image

 

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:

image

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

Tags: ,

MVC | Notes

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading






About me

I love stretching my mind and having a blast in development, since it is a hobby and my profession. More about me on http://www.vrhovnik.net. I do have like to experiment with various toys, project, so i'm in preparation of my own playground, which will be avaliable on http://projects.preliator.net/bojanv.

Month List

Widget Twitter not found.

Root element is missing.X