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 Responses to “jQuery Form Validation with Styles from Twitter Bootstrap”

  1. Graham

    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. David Cochran

    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. David Cochran

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

  4. Giedrius

    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. Mike Fosbrook

    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. Rosemarie Villacorta

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

  7. David Cochran

    Thanks Rosemarie. Appreciate the feedback.

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

  8. Bentzy

    Thank You!

    Did you test it on bootstrap modals?

  9. shivank

    How can we add user defined new rule to bootstrap validation?

  10. shivank

    How can we add new rule to bootstrap validation?

  11. Amit

    great friend

    This is really helpful and a resource for us.

    Thank you very very much

  12. Philippe Kouao

    awesome. thanks a zillion for sharing this

  13. Viperz0r

    Awesome!!! This gonna rock in my school project!

  14. vivek.s

    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 :)

  15. vivek.s

    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 :)

  16. Julian

    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

  17. Jim d.

    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

  18. Chris Koster

    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?

  19. Saurabh Agrawal

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

  20. Renato

    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​​.

  21. Andy

    It’s a cool concept, but why allow folks to leave “223400—2”’??” as a name?

  22. Vikrant

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

  23. Martin from Germany

    This is an excellent example. Thank you for publishing. It helped me lot.

  24. Guy

    exactly what i was looking for and works perfectly.

    thank you very much.

  25. Elena K.

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

  26. zarg

    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?

  27. SEO

    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?

  28. sitakanta

    why there is a cancel button in the demo if its dnt work atall ??

  29. JustinHay | Best Bootstrap Resources

    […] CI+Bootstrap project CUSTOM ICON SET TUTORIAL How to Create a Custom Icon Set for Bootstrap JQUERY VALIDATE W/ BOOTSTRAP How to integrate the jQuery validate plugin with Bootstrap Styles GOLDEN BOOTSTRAP Golden […]

  30. Marcelo

    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));”

  31. iJussie | Best Bootstrap Resources

    […] CI+Bootstrap project CUSTOM ICON SET TUTORIAL How to Create a Custom Icon Set for Bootstrap JQUERY VALIDATE W/ BOOTSTRAP How to integrate the jQuery validate plugin with Bootstrap Styles GOLDEN BOOTSTRAP Golden […]

  32. Jeff

    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);
    }
    });

  33. Kev

    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

  34. Arild Orholm

    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!

  35. Arild Orholm

    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.

  36. zutico

    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

  37. Gina

    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,

  38. William Entriken

    This is great. Please consider removing the image and using font-awesome, to minimize number of resources needed

  39. Nasrullah Shamim

    Thanks a lot for the very useful JQuery plugin!

  40. Matthew Trow

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

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

  41. Sreejith

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

  42. Christoph

    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

  43. Alex

    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!

  44. Vince

    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?

  45. Vince

    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?

  46. Vince

    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>
    <div class=”input-prepend”>
    <span class=”add-on”><i class=”icon-user”></i></span><input id=”nameField” name=”nameField” placeholder=”Your Full Name” style=”width: 201px;” type=”text” />
    </div>
    <label for=”emailField”>Email Address</label>
    <div class=”input-prepend”>
    <span class=”add-on”><i class=”icon-envelope”></i></span><input id=”emailField” name=”emailField” placeholder=”Your Email Address” style=”width:201px;” type=”text” />
    </div>
    <label for=”subjectField”>Subject</label>
    <div class=”input-prepend”>
    <span class=”add-on”><i class=”icon-hand-down”></i></span><select id=”subjectField” name=”subjectField” style=”width:214px;”>
    <option value=”” selected=””>Choose One</option>
    <option value=”service”>General Customer Service</option>
    <option value=”suggestions”>Suggestions</option>
    <option value=”product”>Product Support</option>
    </select>
    </div>
    <label id=”messageField”>Message</label>
    <div class=”input-prepend”>
    <textarea class=”input-xlarge” id=”messageField” name=”messageField” style=”width:229px;” rows=”5″></textarea>
    </div>
    <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:
    <script>
    $.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.”
    },
    }
    });
    });
    </script>

    Hope this helps someone else, cheers.

  47. Bob

    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

  48. Ang Way Chuang

    Thanks, David. This is really useful.

  49. GJ

    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?

  50. krishna

    Thank you very much!!. I got what i was searching for…

  51. Anon

    Is there a version that supports bootstrap 3? Is it going to be released anytime soon???

  52. Milton Rodrigues Jr

    Thanks Man, you save my life with this example!

  53. Manthan

    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

  54. Up Allnite

    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?

  55. vidya

    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

  56. yudi

    how to apply this validation in bootstrap modal.? please share. thanks.

  57. mixer

    Hello,

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


    Cheers,
    Mixer

  58. Hap

    “See the Demo” and “Get the Sample Files” buttons/links are broken.

Leave a Reply