Feb 5, 2013
This tutorial, the demo, and the jQuery code have been updated in light of excellent recommendations made by commenters.
Thanks all!
The 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.
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.
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.
And to be clear, credits for the jQuery Validate plugin go to Jorn! My contribution is just the tut.
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’);
},
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’);
}
},
thanks for this nice form validation :)) so far i’m a newbie of using twitter bootstrap and i’ll try this one …
Thanks Rosemarie. Appreciate the feedback.
And extra thanks to Giedrius and Mike for the tips for improvement.
Thank You!
Did you test it on bootstrap modals?
Works great for me ! Thanks.
I notice Giedrius’ fix is necessary.
How can we add user defined new rule to bootstrap validation?
How can we add new rule to bootstrap validation?
very nice.
great friend
This is really helpful and a resource for us.
Thank you very very much
awesome. thanks a zillion for sharing this
Awesome!!! This gonna rock in my school project!
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 🙂
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 🙂
Great plugin! You save my life with this (really).
Thanks.
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
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
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?
Just Great and Clean !!!
Thank you very mucho !!!.
nice another useful bootstrap addons
Perfect! Just what I was looking for. Loving the Bootstrap…
Great site too!
Great..!!!.. That’s exactly what I was looking for. You saved lots of time..thanks..
Great Tutorial ,Thanks 😉
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.
Hi all! At long last I’ve made the time to update the jQuery to adapt better to cases where a user changes input content from valid to invalid, or vice versa. Thanks again for the catch, Giedrius!
I’ve also taken Jim d’s advice, to swap out ‘label’ for element.
It’s a cool concept, but why allow folks to leave “223400—2”’??” as a name?
If I want to dynamically change the rules based on drop down value selected, How can I do using this?
Hi Vikrant. I’m a bit short on time to investigate this. If you’ve already worked through the plugin’s own documentation, I’d suggest StackOverflow as a great place to ask this question. It may have even been asked and answered over there, as they currently have nearly 3,000 questions tagged with jquery-validate.
Great!
Thanks!
This is an excellent example. Thank you for publishing. It helped me lot.
exactly what i was looking for and works perfectly.
thank you very much.
David, thank you very much for this! Nice plugin and very good explanation.
You save my life with this too! 🙂
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?
Working great thanks for the code
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?
why there is a cancel button in the demo if its dnt work atall ??
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));”
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);
}
});
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
Beautiful. Thanks Kev!
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!
thank you buddy 🙂
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.
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
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,
This is great. Please consider removing the image and using font-awesome, to minimize number of resources needed
Thanks a lot for the very useful JQuery plugin!
great work !!!
WOW!!!!!!!….total helpfull
You can also use the bootstrap error text by adding the following:
errorClass: ‘help-inline’,
errorElement: “span”,
thank you – just what I needed!
Thank You so much David…..I am really new to Jquesry but your demo was really helpful for me.
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
Christoph — Thanks for your note and question. The demo code is open source and free to use. The icons are from the silk set by famfam. Creative Commons attribution license. Information here: http://www.famfamfam.com/lab/icons/silk/
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!
thank.. great plugin
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?
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?
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.
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
Thanks, David. This is really useful.
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?
Thank you very much!!. I got what i was searching for…
Thanks you so much for the code….Much appreciated
Is there a version that supports bootstrap 3? Is it going to be released anytime soon???
Thanks!!
Thanks Man, you save my life with this example!
Thanks man, awesome job!
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
Awesome man, thanks!
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?
where can I get suitable php code for it
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
Great tutorial. inspired by you – I’ve post a little details on my site.
Please check :
http://twitterbootstrap.org/bootstrap-form-validation/
thanks
nice like it
how to apply this validation in bootstrap modal.? please share. thanks.
Hello,
What about radio buttons? Could you provide any example?
When I try it error message appears just under first radio button.
—
Cheers,
Mixer
unable to see the demo. file not found error.
“See the Demo” and “Get the Sample Files” buttons/links are broken.
Dear all, the Demo and Code went missing for a bit after migration. They’ve been restored now!