This is a tutorial on how to write a live validation script for HTML form inputs using jQuery. There are plenty of these out there already, but in most cases I found that they could not be applied quickly. 9 out of 10 websites that I develop need nothing more than a simple validation to tell the user when an input was left empty or filled in improperly. Once you’ve gotten the hang of this script, it will only take you a couple of minutes to reapply it to each new website that you’d like it on.
All you’ll have to do is type in a list of what fields are required, and then change the CSS style of a class to suite that particular website, and that’s it!
First we’ll start with the HTML and CSS. The script will add a class called “needsfilled” to any fields that don’t pass the validation, so you’ll want to specify how you’d like it to look, and make it stand out so that the user knows something went wrong! Be sure to have included the latest version of jQuery and the script file itself in your header.
#error {
color:red;
font-size:10px;
display:none;
}
.needsfilled {
background:red;
color:white;
}
<form action="mail.php" id="theform" name="theform" method="post">
<p><label for="name">Name</label><br /><input id="name" type="text" value="" name="name" /></p>
<p><label for="email">E-mail</label><br /><input id="email" type="text" value="" name="email" /></p>
<p><label for="message">Message</label><br /><textarea id="message" rows="7" cols="30" name="message"></textarea></p>
<p><input class="submit" type="submit" name="submit" value="Submit Form" /></p>
<p id="error">There were errors on the form, please make sure all fields are fill out correctly.</p>
</form>
Please take note of any ID’s used (theform, email, etc.) because you’ll need those ID’s to stay consistent from within the javascript. The HTML and CSS is pretty self-explanatory, so we’ll move onto the javascript. All of this code will be placed within a $(document).ready(function(){}); so that it’s all loaded when the DOM is loaded.
// Place ID's of all required fields here.
required = ["name", "email", "message"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
First we will setup our variables. Just follow the comments so that you know what goes where. If you are using the same ID’s as this tutorial, then all you really have to change is the list of fields that are required, just follow the format used so that the array isn’t broken.
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
Now for an explanation on the code, taking it line by line. $(”#theform”).submit(function() tells the page to execute the following script whenever someone hits the submit button in the form with ID ‘theform’. Next, we create a ‘for’ loop that will run through as many variables as you defined in the ‘required’ array earlier. The next ‘if’ statement will check to see if the current input field is empty, or if it is equal to the text that we set to appear if the field is empty. If either of these cases are true, then it adds the class ‘needsfilled’ to the empty input, replaces its value with the value of ‘emptyerror’, and then fades in ‘errornotice’ alerting the user that something went wrong. If the case is false, then we make sure to remove the class ‘needsfilled’ from the input because that is what we will use later on to see if the form is safe to be submitted.
// Validate the e-mail.
if (!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
Just about every form is going to ask for an e-mail address, so I felt it was necessary to include this bit. This is a regular expression which is filtering the value of the ‘email’ input. It is making sure that the e-mail adress follows the format of “email@domain.something”. NetTUTS has many awesome explanations of regular expressions if you would like more information on them. After this ‘if’ statement is where you would also place any other validation that you’d like, such as checking a URL string for proper formatting.
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
With the above code, we are closing the $(”#theform”).submit(function() at the end. The first if statement is going to be checking to see if ANY inputs on the page have the class ‘needsfilled’. If it does, then ‘return false’ tells the form to not submit.
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
This block is just a little bit of user experience improvement. If a user clicks on an input field that did not pass the validation, then the value will clear so that the user can immediately start typing without having to delete our message. Updated this portion on 10-27-09 a bit, thanks Tom for the suggestion.
And there you have it, quick and simple live form validation that you can easily add within a couple minutes, and hopefully you learned something while you were at it!
As per normal, great work! The only thing I can think of that could be done better would the if the email validation detected if it is a valid email address.
Thanks! I think the only that you can accomplish that is by sending the mail (via PHP for example, if that’s the server side language you’re using) and checking to see if it doesn’t bounce. With javascript, the best you can do is just verify that the e-mail address is formatted correctly, OR use AJAX to check against a database to see if the e-mail has already been used when doing something like registering an account.
Does this work with radio buttons, check boxes and select menus and lists, or is this for text fields and text area?
This is just set up for input boxes. If you’d like to add other things like checkboxes, you’ll need to add additional checks for those. With jQuery, you can have it verify to see if any checkboxes are checked with something like:
if (!$(’:checkbox’).attr(’checked’)) {
do something if there are no checkboxes checked;
};
It should be pretty similar for radio buttons, etc.
In my opinion jquery validate plugin, is easier to use, but it might not be that small
You’re right, the original jQuery validate plugin is pretty awesome and easy to implement since all you have to do is give the required inputs a CSS class, and it has a lot more features. The big emphasis for this, though, was the “small” - 1100 lines of code vs. this script’s 50.
It’s also a situational thing. Having it change the input values, as opposed to making a line of text appear that alerts the user, can come in handy in times when you are limited on space for the form.
Thanks Joren! Good stuff!
wonderful read, keep up the great work. more writers like you are needed on the net
hmm… Downloading now.
enjoyed the read, i will bookmark your page and share it with my friends
Nice post..Keep them coming
Thanks for sharing.
Thanks for sharing ur code and ur views.
I’ve been adapting your code to my webapp. It works like a charm. Except for 2 warnings I get in the js console “Unknown pseudo-class or pseudo-element ‘input’.” Same for textarea.
Your demo has the very same warning. Any clues of what it could be?
Hmmm, try putting a colon in before the input or textarea, like (’:input’)
Let me know if that fixes the error and I’ll update the code. Thanks!
Well, the post is really the freshest on this noteworthy topic. I concur with your conclusions and will thirstily look forward to your forthcoming updates. Saying thanks will not just be adequate, for the wonderful clarity in your writing. I will right away grab your rss feed to stay privy of any updates. Genuine work and much success in your business dealings!
very informative thank you for a nice site
Thanks for this tutorial, which gave me a start into that subject. I have a remark on the last code snippet. Maybe i am missing something, but there seems to be an error in this line (firebug is also telling me so):
> $(”:input”).add($(”:textarea”)).focus(function(){
adding :textarea is unnessesary and probably even wrong. I didn’t find it listed in the jQuery-API and the API-Doc about the :input Selector says, that textareas are also selected with :input. -> http://api.jquery.com/input-selector/
Hmm you could be right, I must have had some reasoning for doing that but I’ll check on it and see if it was even necessary. Thanks for posting!
Yup, jQuery 1.4.2 even throws up an error if you use :textarea, so I took that out of the script. Thanks for pointing that out.
Thank you so very much for that extraordinarily 1st class editorial!
thanx !
I have a question about how to add the e-mail address the form sends to. It seems to be something you set in mail.php? Where can I find that?
@PineGirl: just create a file called mail.php in the same dir as the project files and get it to just echo the incoming $_REQUEST var, for instance with something like…
echo ”.var_export($_REQUEST, true).”;
Hi Joren,
Nice tutorial.
Because I am new on this subjects, how can I validate a List/Menu using this javascript?
Here is my code for this list/menu:
Tema A / 23 Novembro 14h-18h
Tema B / 24 Novembro 9h-13h
Tema C / 24 Novembro 14h-18h
Thanks
Best regards
Miguel
proffesional service is a must
Very useful. Although for some reason best known to itself, as it’s not producing any errors, the input.focus() function isn’t doing anything at all. The offending input fields do have the “needsfilled” class applied to them. (did I mention that I hate javascript?)
Solved it myself. Have to move the function out of the submit function block and give it live() as well (since it’s all loaded via AJAX and doesn’t exist yet on document load).
Also had to move the definitions for the email field into the submit function so it would be valid under the live() function. Probably could have used live() on the definitions as well; easier to just move the variable definitions inside the submit function.
Very helpful and easy to implement.
thanks!
Thank you. Precisely what I was looking for for a one-page contact site. Love the extended options, but this saved me the time to clean stuff out.
Hi,
thanks, this is a really nifty piece of code. In my case, because I already have several other jquery depencies and CSS it turns out as I embedded this one, it completely covered the whole page in blank, so my webpage was gone from sight. Yes, I renamed the “container” as I already had one div for container before I included yours, I changed that in the stylesheet and in the body, yet no change. I looked at the z values, and mine were in the 1000 while you are moving on the 10, 11, so in principle mine should have shaded yours. The general problem that is happening is that the CSS end up conflicting and the whole page is messed up. What do you do to avoid that ? It is particularly bad because now the trend is about embedding someone else’s script because one cannot write things from scratch again, but then, these problems …
thank you
Al
Thanks a lot for this tutorial!
Nice post.. quite easy to follow. Keep them coming.
Hi,
I like the idea of your code, but I’m having the same problem as Pineagirl.
My form won’t work because of a missing mail.php file which you don’t include in your download. You haven’t mentioned it once in your description. So where does my form go?????? Could you please address these issues in an addendum to the post.
This article was just on javascript validation. You can use whatever PHP or ASP.NET mail script you’d like with it. If you want an extremely basic PHP mail script, you can download the files from this post http://jorenrapini.com/blog/css/jquery-validation-contact-form-with-modal-slide-in-transition and use mail.php, however there is no security on that file.
I didn’t realsie that this was only the validation part. I have now created a simple mail.php file.
I realise I might have security issues with it.
I don’t suppose you could point me in the direction of some validation techniques?
Thanks for the tutorial, I have it working on my site now. Just need to address these issues of security.
Actually, my scripts have evolved quite a lot since this article was written. I just no longer have the time to write new articles, but you can download all of the files together here: http://jorenrapini.com/Valijax/Valijax1.12.zip
There are some instructions on the example files that you can follow.
Hi,
First off, thanks for sharing your scripts. It works great !!!
I have a question and I’d greatly appreciate your help.
My form has text input elements as arrays.
For example:
The form allows the user to add rows dynamically ( that’s why the array is needed )
Now, when “Submit” is clicked, only the first row shows “error messages”.
How do I make sure that blank elements in other rows are also highlighted?
Thanks.
Seems like the post does not allow inclusion of html tags.
In my last post, I included a td tag with id=’amt’ and name=’amt[]‘ attributes, as an example.
I hope this one goes thru.
What do u mean dont tell Rene u can”t spell. None of you guys can spell here at TIPB. You guys alwa ys mess up on ur blogs man.Well really, Google has been doing the minimalistic white page for a long time now. It”s really more their thing than Apple”s.Mine has always done this, I don”t mind. I just wished they changed the callwaiting tone. Others can hear it which bothers me.Well really, Google has been doing the minimalistic white page for a long time now. It”s really more their thing than Apple”s.Mine has always done this, I don”t mind. I just wished they changed the callwaiting tone. Others can hear it which bothers me.Guess I”ve been fortunate enough to not have a sensor issue. My friend still on 4.0.1 however does, guess I”ll recommend this.
Sweet, this is precisely what I was shooting for! Your article just saved me alot of digging around
I’ll make sure to put this in good use! Bookmarked for the good information
Great, thanks. I have been looking for some lightweight code which a jquery noob can understand. I think i’ve found it!
that is gr8
what do you mean by this piece of code at the end of email validation
.test(email.val()))
what is test?
i have tried to put post code validation but it does not work here is my code
if (’~^([1-9]{1}[0-9]{3}\s[A-Z]{2})$~’,postcod.val()) {
postcod.addClass(”needsfilled”);
postcod.val(postcoderror);
}
could any one help plz
Mary, here is an explanation on .test() http://www.w3schools.com/jsref/jsref_regexp_test.asp
Hi,
This email form is great! I followed all the directions and enter the fields correctly, but when i press submit button an error comes up saying ” cannot find main.php file”
can anyone please help.
This code is just for front end validation with jQuery. If you want it to actually send a message, you need to supply a php mail script (in this example, the form’s action is just set to main.php, that’s why you get that message).
thank you very much and responding so quickly
Great tutorial it realy helped me, since I’m a newbie in jquery.I has boosted my confidence to do anything in jquery.Thank you very much. keep up the good work
This is awesome, thank you so much
Was having so much trouble validating my forms before I found this!
Has there been any examples with radio buttons and drop-down menus?
Not yet. If I can find the time to get around to it, I do have a much cleaner script that takes advantage of these. Hopefully soon.
Thank you for this great tutorial. I am having trouble modifing the javascript to have it validate two separate forms in two jquery tabs. I changed the form ids in both the js and the form but still only wants to validate the one form. Can this work with two forms?
Here, this can do the trick for you. Eventually I’ll get around to updating this article with this code. http://jorenrapini.com/Valijax/Valijax1.15.zip
Thank you so much Joren. Cheers!
Thanks a lot,
This is the best tutorial of form validation using ajex i have read. Keep it on friend.
Great tutorial!
Thank you!
Question: How can I add phone number validation?
Pretty nice post. I just stumbled upon your weblog and wished to say that I have really enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon!
Thanks soooo much :). This is much better than other sites ive seen.
Hi
Your demo does not work. Neither do your downloadable files…
It just posts even if you dont fill out any details…
Any idea whats up?
What browser are you using? Everything seems to be working fine, this hasn’t really been changed for a couple of years.
Hi Joren,
Firefox 3.6, 4.0 and also 7
Bob, it seems to work fine on Firefox. What problem specifically are you seeing? Is the console giving you any errors?
this is great validation but how to add phone validation and check box validation. Kindly let us know.
how to make validation for phone No. Kindly Let me know
Here you go, you can add this to the code http://www.sitepoint.com/forums/showthread.php?657877-Phone-Number-Validation
Nice work it helps me a lot .THANX
Hey,
Great script, Thanks alot for this!
Quick question:
How do I implement this twice on one page?
I know it sounds silly but my client was a contact form on the homepage and the footer. So I tried used completely seperate ID’s for both forms, input fields etc but when one form is filled and is submitted, it fails and the other contact form lights up with errors?
Thanks in advance!
Yeah sorry, it just wasn’t built for that. The code needs a lot of tweaks, which I haven’t really had the time to upload.
Oh ok.
Thanks for the fast reply!
thanks Dear it’s so eassy to apply. thank u very much…
hello dear ..
can u help me ? I want submit dynamic form using jquery without refreshing page but many problem is coming. can u provide any simple code ?
Great TUT!