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:

        highlight: function (element, errorClass, validClass) {
        unhighlight: function(element, errorClass, validClass) {
The result
Edit - it was already on StackOverflow for quite some time:

1 comment: