jQuery Form Validation with Styles from Twitter Bootstrap

Feb 5, 2013

This tutorial, the demo, and the jQuery code have been updated in light of excellent recommendations made by commenters.

Thanks all!

jQuery Form Validation ScreenshotThe jQuery Validate plugin by Jörn Zaefferer is a fantastic tool for providing users with immediate feedback while completing a web form. Used by Newsweek and others.

Here I’ve put together a working example, integrated with markup and styles from Twitter Bootstrap’s excellent front-end framework. The demo and sample files include markup, CSS, and JS.

See the Demo

Get the Sample Files

106 thoughts on “jQuery Form Validation with Styles from Twitter Bootstrap

  1. Thanks for the useful JQuery plugin!
    This is a nice site you have. I love the Yoko theme (I use it myself).
    The bootstrap theme looks interesting too. I’ll have to check it out further. I’ve been looking for some good responsive layout themes.

  2. Thanks Graham. Yoko is in fact a great theme (though I’ve not made quite as good use of it as you). I anticipate rolling out a new design at the end of my explorations with the Roots theme. Doubtless it may not be better, but I enjoy the process! And I definitely appreciate the all-purpose combo of styles and behaviors coming wrapped in Bootstrap.

  3. And to be clear, credits for the jQuery Validate plugin go to Jorn! My contribution is just the tut.

  4. You forgot to remove class if user decides to change something and from valid, text-field becomes invalid.

    I think it should be like this:
    highlight: function(label) {
    $(label).closest(‘.control-group’).removeClass(‘success’).addClass(‘error’);
    },
    success: function(label) {
    label
    .text(‘OK!’).addClass(‘valid’)
    .closest(‘.control-group’).removeClass(‘error’).addClass(‘success’);
    },

  5. Giedrius solution works fine. I tried the code below which works, but is unnecessary. You’d think this would be documented better on the validation plugin site given its popularity.

    onfocusout: function(label) {
    if($(label).val() == ”){
    $(label).closest(‘.control-group’).removeClass(‘success’);
    }
    },

  6. thanks for this nice form validation :)) so far i’m a newbie of using twitter bootstrap and i’ll try this one …

  7. Thanks Rosemarie. Appreciate the feedback.

    And extra thanks to Giedrius and Mike for the tips for improvement.

  8. its good…but i am wondering why havent you added this plugin to this feedback form.It throws me server error whe in post without mandatory fields 🙂

  9. its good…but i am wondering why havent you added this plugin to this feedback form.It throws me server error when I post without mandatory fields 🙂

  10. Hi, thanks for the demo. There seems to be a little bug –
    in the “Your name” field, enter a valid name (“SomeThing”), tab out
    click back into the field, remove all the data

    you will now see the “this field is required.” in red, but the label and field are still colored in green

  11. Thanks David! I found one minor ‘bug’. You named the parameter to the highlight function “label”, but actually the validate plugin passes the *input element* to be highlighted. Your code works either way, but if you rename the parameter to something like ‘element’ it’ll be a little more clear, e.g.

    highlight: function(element) {
    $(element).closest(‘.control-group’).addClass(‘error’);
    }

    Either way, a great tutorial. Thanks! –Jim

  12. Hi!

    Your plugin works fine but jQuery validate breaks the Bootstrap input fields with a inline button (class=”input-prepend”). This is because jQuery validate appends an extra label to show the validation message, the Bootstrap markup span is then showd below the input, instead of directly next to it.

    More info on inline button:

    http://twitter.github.com/bootstrap/base-css.html#forms

    Any ideas?

  13. Great..!!!.. That’s exactly what I was looking for. You saved lots of time..thanks..

  14. Good tip, but there are some bugs in the example, for instance, sometimes they add classes error and success but does not remove them after you completed the form but deleted values​​.

  15. If I want to dynamically change the rules based on drop down value selected, How can I do using this?

  16. David, thank you very much for this! Nice plugin and very good explanation.
    You save my life with this too! 🙂

  17. Thank you, David, for an excellent tutorial; beautifully and elegantly presented. But since I don’t use bootstrap (I use the Skeleton responsive framework) do you think it would be possible to use only the styles required for forms, and perhaps copy them to the style.css file? Or is this so integrated with bootstrap that that might not be sensible or practical?

  18. Amazing things here. I’m very glad to look your post. Thank you a lot and I am having a look ahead to contact you. Will you please drop me a mail?

  19. Chris Koster,

    solution for the class “input-input-prepend append” of bootstrap

    Replace the line 655: “: label.insertAfter(elements)” for this “: label.insertAfter(
    $(element).parent().hasClass(‘input-prepend’) || $(element).parent().hasClass(‘input-append’)? $(element).parent()
    :$(element));”

  20. I couldn’t get it to remove the highlight with your example. Below worked for me.

    $(“#contract-form”).validate({
    errorClass: “error”,
    rules: {
    “firstName”: “required”,
    “lastName”: “required”
    },highlight: function(element,errorClass,validClass) {
    $(element).closest(‘.control-group’).removeClass(validClass).addClass(errorClass);
    },
    unhighlight: function(element,errorClass,validClass) {
    $(element).closest(‘.control-group’).removeClass(errorClass).addClass(validClass);
    }
    });

  21. Nice demo. One suggestion:
    I find the demo a bit ‘jumpy’. Twitter Bootstrap error messages are inline so they don’t cause the screen to jump. The jQuery Validate error messages are display:block elements so they push all elements below them down the screen and cause a ‘jumpy’ effect which is difficult to track with the eye. It’s possible to use the twitter styles and stop the screen from jumping by doing this:

    jQuery.validator.setDefaults({
    errorClass : “help-inline” // The twitter error message class
    });

    See example on github:
    https://github.com/KevinSheedy/jQueryValidateTwitterBootstrap

  22. Hey, pretty noob on bootstrap, this is a great form checker and does what I want for the page I am building.

    But being a noob, how do I get this from being a form that submits no info to a form that actually submits info? I expect I have to do the whole .php thing, could anyone please point me in the right direction to a tutorial on this (that could actually easily be combined with this script)? Thanks in advance!

  23. I somehow managed to get this to work just like I wanted, took me a few hours but now I know. This is a great script and a really nice way of doing it.

  24. Hi Dudes,

    Nice work, one minus: when I use a prepend add-on icon it does not move along the input box so a tiny yet annoying effect on success validation.

    I am most certain you can fix that, actually I hope!

    In any case: nice one!

    Cheers,
    Marco

  25. hi! when working with an autocomplete input text field
    something like:

    <input autocomplete="off" class="span3" id="input1" name="input1" type="text" data-provide="typeahead" data-items="8" data-source='["name1","name2"]'….

    i'm trying to validate it, because its required and it's not working
    input1:{
    required: true
    },
    also, is there a way to only allow an input that matches the data source?
    Thanks,

  26. You can also use the bootstrap error text by adding the following:

    errorClass: ‘help-inline’,
    errorElement: “span”,

  27. Thank You so much David…..I am really new to Jquesry but your demo was really helpful for me.

  28. Hi there,

    a really great code snippet! Absolutely neat, thank you.

    But one IMPORTANT question – I want to use your code in a commercial environment, but I couldn’t find any license information. May I use your code? What about the beautiful two icons, do you have all rights on those or do you know the corresponding license?

    Cheers, Christoph

  29. Hello,

    Thank you for this great thing.

    But please could you point out an example with radios? I tried:

    html:

    Mrs.

    Mr.

    JS:

    gender: {
    required: true
    },

    That does nothing…
    Could you please help me? Thank you!

  30. I’m trying to write code based on your work that doesn’t include the graphic check mark or the label tag which accompanies failures or successes. If the field is correct I’d like to leave it with just the ‘success’ class maintained by bootstrap on the div.control-group and clear out all the other messages.

    Problem is, I can not stop this HTML from appearing in the code, even with my modifications to success:

    I’m taking this code:
    success: function(element) {
    element.text(‘OK!’).addClass(‘valid’).closest(‘.control-group’).removeClass(‘error’).addClass(‘success’);
    }

    and rewriting it like this:
    success: function(element) {
    element.closest(‘.control-group’).removeClass(‘error’).addClass(‘success’);
    }

    The ‘.removeClass(‘error’)’ has to be there incase any pre-existing error messages need to be removed first but in cases where no error previously existed running the ‘success’ call still insists on writing this HTML back to the browser:

    I’ve also tried this without success:
    success: function(element) {
    element.closest(‘.control-group’).addClass(‘success’).closest(‘label’).remove();
    }

    I’m no JavaScript pro, can someone tell me what I’m missing here?

  31. HTML codes not converted automatically on this blog I guess, here it is again.

    I’m trying to write code based on your work that doesn’t include the graphic check mark or the label tag which accompanies failures or successes. If the field is correct I’d like to leave it with just the ‘success’ class maintained by bootstrap on the div.control-group and clear out all the other messages.

    Problem is, I can not stop this HTML from appearing in the code, even with my modifications to success:
    <label for=”name” class=”error”></label>

    I’m taking this code:
    success: function(element) {
    element.text(‘OK!’).addClass(‘valid’).closest(‘.control-group’).removeClass(‘error’).addClass(‘success’);
    }

    and rewriting it like this:
    success: function(element) {
    element.closest(‘.control-group’).removeClass(‘error’).addClass(‘success’);
    }

    The ‘.removeClass(‘error’)’ has to be there incase any pre-existing error messages need to be removed first but in cases where no error previously existed running the ‘success’ call still insists on writing this HTML back to the browser:
    <label for=”name” class=”error”></label>

    I’ve also tried this without success:
    success: function(element) {
    element.closest(‘.control-group’).addClass(‘success’).closest(‘label’).remove();
    }

    I’m no JavaScript pro, can someone tell me what I’m missing here?

  32. Hi David, ty for writing this article. It helped me develop my own idea how best to integrate forms with jquery and bootstrap based websites. Much of my final coding decisions were based on the second example found on Jörn Zaefferer demo page at http://jquery.bassistance.de/validate/demo/. Here’s what I ended up doing.

    Resources:
    Bootstrap v2.3.2
    jQuery v2.0.2
    jQuery Validation Plugin v1.11.1

    My Form:
    <form class=”well” id=”contactUsForm” style=”float: left; margin-right: 20px; width: 243px;”>
    <legend>Contact Us Form</legend>
    <label for=”nameField”>Name</label>

    <label for=”emailField”>Email Address</label>

    <label for=”subjectField”>Subject</label>


    Choose One
    General Customer Service
    Suggestions
    Product Support

    <label id=”messageField”>Message</label>

    <button class=”btn btn-primary” style=”float:right;” type=”submit”>Send</button>
    </form>

    My CSS:
    <style type=”text/css”>
    label.error {
    color: red;
    margin: 2px 0 0;
    width: 243px;
    }
    .input-prepend { white-space: normal; }
    textarea { margin-bottom: 0px; }
    </style>

    My JavaScript:

    $.validator.setDefaults({
    submitHandler: function() { alert(“submitted!”); }
    });
    $().ready(function() {
    // validate signup form on keyup and submit
    $(“#contactUsForm”).validate({
    rules: {
    nameField: “required”,
    emailField: {
    required: true,
    email: true
    },
    subjectField: “required”,
    messageField: {
    required: true,
    maxlength: 512
    }
    },
    messages: {
    nameField: “Please enter your name.”,
    emailField: “Please enter a valid email address.”,
    subjectField: “Please choose a subject.”,
    messageField: {
    required: “Please tell us what’s on your mind.”,
    maxlength: “Please try to keep your messages to 512 characters or less.”
    },
    }
    });
    });

    Hope this helps someone else, cheers.

  33. Hi David

    Thanx for an incredibly useful piece of coding

    Feature creep question!!

    I have a amend customer details form and the form elements are loaded by AJAX via a dropdown of all customers. If there are any warnings up and the customer is changed the warnings don’t refresh. Is there anyway of calling the code via an onchange=”” statement?

    Cheers

    Bob

  34. Non-required input fields

    Hi, thanks for this tutorial, it was very helpful!
    I still have one question, how can I display a ‘success’ for input fields that are not required (optional fields)? For instance, I have a ‘Building number Suffix’ input field, which is optional. When the user fills in the form, he receives green marks everywhere but not at the suffix field. How can I fix it so the user’s input still looks valid?

  35. Thanks a lot..

    We were looking for this sort of form since long. We wanted to use it for our portal Oshopindia.

    Thanks
    Manthan
    Oshopindia.com

  36. I’m trying to incorporate your code for a pretty basic contact form.
    http://www.estherlee.co/clientproj/cns/tests/contact.html

    It’s really great, except for one big problem so far: I have a “reset” button and when I do a test to try to clear the form the added classes of “valid” and “error” stay put no matter what I try: var validator = $(‘#myForm’).validate({rules, messages, submitHandler}); validator.resetForm(); doesn’t work, and neither does adding a specific click function for the reset/cancel button. I noticed your “Cancel” button behaves the same way (eg, doesn’t clear the generated “label” div or associated “valid”, “error”, “success” classes, just the form data).

    This seems to be a fairly common issue on StackOverflow. Any chance you have a solution?

  37. hi your plugin s superb bt i have one doubt can any 1 please solve it

    i want trim option for email verification like if user gives space after r before mail id it should ignore it

    so please any one help me out to solve this prob wht shd i change in this code

  38. Hello,

    What about radio buttons? Could you provide any example?
    When I try it error message appears just under first radio button.


    Cheers,
    Mixer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s