fredag 5 april 2013

jQuery Validation not working in ASP.NET MVC solution

I was implementing a simple register user form the other day and had some difficulties getting the jQuery Validation framework to work. The view code was really straight forward:
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.UserName)
</div>
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.EmailAddress)
</div>
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.Password)
</div>
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.ConfirmPassword)
</div>
<input type="submit" data-role="button" data-theme="b" value="Register" />

And the model to validate looks like this:
public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
    [Display(Name = "Email")]
    public string EmailAddress { get; set; }
}

When submitting an empty form only the server side validation kicked in. After a few hours of trial-and-error I found out that apparently you have to add a validation message for EVERY field in the form which are about the get validated. Updating my view to this solved my problems:
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.UserName)
    @Html.ValidationMessageFor(m => m.UserName, "*")
</div>
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.EmailAddress)
    @Html.ValidationMessageFor(m => m.EmailAddress, "*")
</div>
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.Password)
    @Html.ValidationMessageFor(m => m.Password, "*")
</div>
<div data-role="fieldcontain">
    @Html.EditorFor(m => m.ConfirmPassword)
    @Html.ValidationMessageFor(m => m.ConfirmPassword, "*")
</div>
<input type="submit" data-role="button" data-theme="b" value="Register" />

Hopefully this blog post will help others in the same situation :)
/Erik