views:

61

answers:

1

Let's say I have a model that looks like this:

public class MyModel
{
    [DisplayName("Email:")]
    [Required(ErrorMessage = "Email is required")]
    [Email(ErrorMessage = "Email is invalid")]
    public string Email { get; set; }
}

In ASP.NET MVC 2, I'd render the text box and validation like so:

<%=Html.LabelFor(x => x.Email)%>
<%=Html.TextBoxFor(x => x.Email)%>
<%=Html.ValidationMessageFor(x => x.Email)%>

How do I add a second field to allow the user to confirm their email address using the display name and validation from the model's property?

A: 

Decorate your Class with the following Attribute:

    [PropertiesMustMatch("Email", "ConfirmEmail", ErrorMessage = "The Email Address and confirmation Email Address do not match.")]
    public class MyModel
    {
        [DisplayName("Email:")]
        [Required(ErrorMessage = "Email is required")]
        [Email(ErrorMessage = "Email is invalid")]
        public string Email { get; set; }

        [DisplayName("Confrim Email:")]
        [Required(ErrorMessage = "Email is required")]
        [Email(ErrorMessage = "Email is invalid")]
        public string ConfirmEmail { get; set; }
    }

You can get the PropertiesMustMatch Helper class here: http://www.polemus.net/2010/09/mvc-confirm-username-password.html

You will also notice that if you create a new MVC2 Project the AccountModel has an example of this.

Dusty Roberts
And where does that validation message show up in the view? I'm not using Html.ValidationSummary anywhere on the page...
Chris
Have a look at: ModelState.AddModelError, there you can add error messages, i believe it will look something like this: ModelState.AddModelError("ConfirmEmail", "Does Not Match");
Dusty Roberts