I have the following (abridged) DTO for registering a new user:
[PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")]
public class RegisterModel
{
//.....
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
}
This is then wrapped in a View Model as such:
public class RegisterModelViewData: BaseViewData
{
public RegisterModel RegisterModel { get; set; }
public int PasswordLength { get; set; }
}
And finally, on the view, I have the two fields as such:
<div class="editor-field">
<%= Html.PasswordFor(m => m.RegisterModel.Password) %>
<%= Html.ValidationMessageFor(m => m.RegisterModel.Password) %>
</div>
<div class="editor-field">
<%= Html.PasswordFor(m => m.RegisterModel.ConfirmPassword) %>
<%= Html.ValidationMessageFor(m => m.RegisterModel.ConfirmPassword) %>
</div>
Apparently, I am supposed to get a client side validation, and no post, if the passwords don't match. I get a post and then a message that "Account creation wAs unsuccessful", but nothing about mis开发者_Go百科matched passwords. I have omitted the Required and MininumLength attributes from the password proeprties here for brevity, but they seem to behave as expected and validate on the client.
Now available in ASP.MVC 3 in case anyone is still wondering
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Passwords must match")]
public string ConfirmPassword { get; set; }
PropertiesMustMatch is a type validator, not a property validator, and MVC doesn't support client-side validation for type validators, only for property validators. In his fascinating blog post, ASP.NET MVC: Adding client-side validation to PropertiesMustMatchAttribute, Stuart Leeks describes how to implement a MustMatch property validator that uses client-side validation and can be used to ensure two properties match, e.g. for password confirmation.
精彩评论