Thursday, December 13, 2012

Using jquery.validate.unobtrusive with Twitter Bootstrap

I'm a fan of Twitter bootstrap! I love the looks and the cleanliness of the HTML and css. I'm also a fan of the unobtrusive validations in ASP.NET MVC. So, I tried combining the two, and it turns out to be as easy as 1,2,3.

Here's a snippet with displaying a person object. I'm using the layout that Bootstrap uses too ( with the control-div around the label and input )

Edit person @Model.Name

@using (Html.BeginForm(this.Html)) {
Fields @Html.HiddenFor(person => person.Id)
@Html.LabelFor(person => person.Name, new {@class="control-label"})
@Html.TextBoxFor(person => person.Name) @Html.ValidationMessageFor(person => person.Name, null, new { @class = "help-inline"})
@Html.LabelFor(person => person.Age, new {@class="control-label"})
@Html.TextBoxFor(person => person.Age) @Html.ValidationMessageFor(person => person.Age, null, new { @class = "help-inline"})
}


And here's the only thing required to make unobtrusive validations work with this markup:

    $.validator.setDefaults({
        highlight: function (element, errorClass, validClass) {
            $(element).closest(".control-group")
                .addClass("error");
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).closest(".control-group")
                .removeClass("error")
                .addClass("success");
        }        
    });
 
The result
Edit - it was already on StackOverflow for quite some time: http://stackoverflow.com/questions/10217175/mvc-twitter-bootstrap-unobtrusive-error-handling

1 comment: