Twitter Bootstrap validation styles with ASP.NET MVC

Well it’s been a while since I’ve been blogging, two kids under 2 will do that to you. I’m going to try and get back into writing some regular posts.

Recently I’ve been playing around with Twitter Bootstrap, so the first thing I wanted to do was add it to an ASP.NET MVC 4 project. Getting the project set up was all pretty easy, and I quickly created a form using the horizontal form styles.

When it came to validation I needed to add a class to the control group container divider.  jQuery Validate allows you to override some of the default options using the setDefaults function. The ones I need to override are highlight and unhighlight. These two functions are used to add the errorClass and validClass to the element being validated.

To start with here is my form markup:

@using (Html.BeginForm(null, null, FormMethod.Post, new { @class="form-horizontal" }))
{
    <div class="control-group">
        @Html.LabelFor(m => m.Forename, new { @class="control-label" })
        <div class="controls">
            @Html.TextBoxFor(m => m.Forename)
            @Html.ValidationMessageFor(m  => m.Forename, null, new { @class="help-inline" })
        </div>
    </div>
    <div class="control-group">
        @Html.LabelFor(m => m.Surname, new { @class="control-label" })
        <div class="controls">
            @Html.TextBoxFor(m => m.Surname)
            @Html.ValidationMessageFor(m  => m.Surname, null, new { @class="help-inline" })
        </div>
    </div>
    <div class="control-group">
        @Html.LabelFor(m => m.Email, new { @class="control-label" })
        <div class="controls">
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m  => m.Email, null, new { @class="help-inline" })
        </div>
    </div>
    <div class="control-group">
        @Html.LabelFor(m => m.Password, new { @class="control-label" })
        <div class="controls">
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m  => m.Password, null, new { @class="help-inline" })
        </div>
    </div>
    <div class="control-group">
        @Html.LabelFor(m => m.ConfirmPasword, new { @class="control-label" })
        <div class="controls">
            @Html.PasswordFor(m => m.ConfirmPasword)
            @Html.ValidationMessageFor(m  => m.ConfirmPasword, null, new { @class="help-inline" })
        </div>
    </div>

    <div class="form-actions">
      <button type="submit" class="btn btn-primary">Save changes</button>
      <button type="button" class="btn">Cancel</button>
    </div>
}

I’m just using the documented Bootstrap markup and adding the necessary classes to the label and validation span.

Next my implementations of the jQuery Validate functions (I took the default implementation and added by code to add and remove classes to the control group):

jQuery.validator.setDefaults({
    highlight: function (element, errorClass, validClass) {
        if (element.type === 'radio') {
            this.findByName(element.name).addClass(errorClass).removeClass(validClass);
        } else {
            $(element).addClass(errorClass).removeClass(validClass);
            $(element).closest('.control-group').removeClass('success').addClass('error');
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        if (element.type === 'radio') {
            this.findByName(element.name).removeClass(errorClass).addClass(validClass);
        } else {
            $(element).removeClass(errorClass).addClass(validClass);
            $(element).closest('.control-group').removeClass('error').addClass('success');
        }
    }
});

And that’s it! Nice Bootstrap styles for valid and invalid fields:

Posted on by Joe in ASP.NET, C#, jQuery, MVC

8 Responses to Twitter Bootstrap validation styles with ASP.NET MVC

  1. Leniel Macaferi

    Hey Joe,

    Hope you’re well with your family! :)

    The code you provide in this post is the best so far on the internetz.

    One thing I did was to add a piece of code I got here http://www.braindonor.net/blog/integrating-bootstrap-error-styling-with-mvcs-unobtrusive-error-validation/381/ in jQuery.(document).ready():

    $(‘span.field-validation-valid, span.field-validation-error’).each(function ()
    {
    $(this).addClass(‘help-inline’);
    });

    This way you avoid having to manually add the class help-inline to each validation message.

    All the best and keep sharing. This is the secret for a better world…

    Best,

    Leniel

  2. Joe

    Hi Leniel

    Thanks for the input. The other way I had thought to do it was to create some custom bootstrap HTML helpers.

    Cheers
    Joe

  3. SiafuDEV

    where do you change the jQuery Validation code ?

  4. Björn

    Hi Joe,

    thanks for the Code. I have change it for Bootstrap 3, you can see the code in my blog (german) under http://www.welt-held.de/2670-asp-net-mvc-bootstrap-3-0-client-validierung.html
    You can use the code here if you want!

    Greets
    Björn

  5. Lesław

    Good job. I was searching for a simple and elegant solution for getting MVC4 working with Bootstrap and your approach did the trick. This saved me a lot of pain.

  6. Jay

    Updated for BootStrap 3

    jQuery.validator.setDefaults({
    highlight: function (element, errorClass, validClass) {
    if (element.type === ‘radio’) {
    this.findByName(element.name).addClass(errorClass).removeClass(validClass);
    } else {
    $(element).addClass(errorClass).removeClass(validClass);
    $(element).closest(‘.form-group’).removeClass(‘has-success’).addClass(‘has-error’);
    }
    },
    unhighlight: function (element, errorClass, validClass) {
    if (element.type === ‘radio’) {
    this.findByName(element.name).removeClass(errorClass).addClass(validClass);
    } else {
    $(element).removeClass(errorClass).addClass(validClass);
    $(element).closest(‘.form-group’).removeClass(‘has-error’).addClass(‘has-success’);
    }
    }
    });

    You can add this code right after you load jquery, jqyuery validate and Unobtrusive validation files.

  7. Me

    jQuery.validate and Microsofts unobtrusive validation don’t play well together:

    http://www.tigraine.at/2011/08/26/jquery-validate-and-microsofts-unobtrusive-validation-dont-play-well-together

    https://gist.github.com/remi/957732

    I have problems related to that…

  8. daniel

    I don’t know how to use this code, could you explain step by step how to use this code, where we should put this code? I’m new in jquery

Add a Comment