Wednesday, July 28, 2010

ASP.NET MVC: Adding client-side validation to ValidatePasswordLengthAttribute

When you create a new ASP.NET MVC 2 project in Visual Studio there are a number of files that are created. One of these is AccountModel.cs. If we ignore the fact that this one file contains multiple classes (I’ve no idea why!), we will see that there is some nice example code lurking in there. One such piece of code is the ValidatePasswordLengthAttribute. This attribute can be applied to your model to enforce a minimum password length (based on the minimum specified by the currently configured MembershipProvider). The code below shows the attribute usage (taken from ChangePasswordModel):

       [Required]
       [ValidatePasswordLength]
       [DataType(DataType.Password)]
       [DisplayName("New password")]
       public string NewPassword { get; set; }

This lets us take advantage of the model binding and validation that is baked into ASP.NET MVC 2. One nice feature of the validation is that the built in validators make it very easy to enable client-side validation by adding the following line to your view:

<% Html.EnableClientValidation(); %>

With this in place, ASP.NET MVC will emit the necessary javascript to wire up the client-side validators (you need to reference the script files from your view). Scott Guthrie has a good blog post that goes through the in-built validation in more depth – the remainder of this post will look at adding creating your own custom client-side validation.

If you enable client-side validation for the ChangePassword view (the snippet above) then you will find that the required field validation is triggered in the browser but the minimum length validation only happens on a postback. This is because the in-built Required validator has client-side support, but the ValidatePasswordLength supplied as part of the template doesn’t.

So, how do you go about adding client-side validation? That’s what the rest of this post will cover.

Read more: Stuart Leeks

Posted via email from .NET Info