Talk to me about anything. If you’d like to work with me, or
even if you just need a hug, I’ll get back to you shortly.

Please enter your name

Please enter a valid e-mail

It's cold!

Say something!

The Simple, Quick, and Small jQuery HTML Form Validation Solution

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 (!/^S+@S+.S+$/.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!

105 Comments
  1. Jim Bouschor

    I love the simplicity of the code and it works great. But i have a question:

    For required fields, what about disallowing leading whitespaces? For instance, i have a required Name field. If the user just puts a few spaces in, then the field validates. It should really require letters only or at the very least not allow a leading space in the field.

    Thx man. Great work!

    March 16, 2012 at 10:29 am
    Reply

    • This would help [adding .replace(/ /g,'') for removing white space]

      if ((input.val().replace(/ /g,”) == “”) || (input.val() == emptyerror))

      March 27, 2012 at 10:39 am
      Reply

      • Greenwood Man

        Hi

        The validation system works fine but the following syntax for removing white space causes error in validation.js

        //Validate required fields

        for (i=0;i<required.length;i++) {
        var input = $(’#'+required[i]);
        if ((input.val().replace(/ /g,”) == “”) || (input.val() == emptyerror))
        input.addClass(”required”);
        input.val(emptyerror);
        errornotice.fadeIn(750);
        } else {
        input.removeClass(”required”);
        }
        }

        // Validate the e-mail.

        What could be the reason? How to overcome it?

        Thanks in advance.

        March 29, 2012 at 7:55 am

      • pierre

        Hi,

        correct is

        if ((input.val().replace(/ /g,”") == “”) || (input.val() == emptyerror))

        September 8, 2012 at 10:04 am

  2. Greenwood Man

    The validation system works fine but the following syntax if ((input.val().replace(/ /g,”) == “”) || (input.val() == emptyerror)) for removing white space causes error in validation.js

    //Validate required fields

    for (i=0;i<required.length;i++) {
    var input = $(’#’+required[i]);
    if ((input.val().replace(/ /g,”) == “”) || (input.val() == emptyerror)) {
    input.addClass(”required”);
    input.val(emptyerror);
    errornotice.fadeIn(750);
    } else {
    input.removeClass(”required”);
    }
    }

    // Validate the e-mail.

    What could be the reason? How to overcome it?

    Thanks in advance.

    March 29, 2012 at 7:58 am
    Reply

  3. Sean

    Hi Joren,
    Great tutorial, thank you for sharing this code. It’s elegance is in it’s simplicity. I noticed that you have some updated code for AJAX, but I was wondering: for this original version of the code, in the else part of the function where it hides the errormessage and sets the submit button to (return true;), is it possible to do two other things - I am trying to a) hide the container div that the form is in and b) show a hidden div.

    This is a simple enough task to achieve on it’s own and I have a version working but I am NOT able to achieve this in this validation code. I tried adding something like this:

    errornotice.hide();
    return true;
    $(”#placeHolder #myForm”).hide();
    $(”#placeHolder #stuff”).show();

    But it doesn’t work; I am new enough at jQuery that I don’t properly understand the syntax, or the proper way to do this - do I need to wrote a new function and can it be called in this fashion?

    Thans to you (or any commenter) that can help with this.

    April 23, 2012 at 2:07 pm
    Reply

  4. Brandon

    One big problem: it removes the invalid field value, so if (for instance) you just mistyped your long e-mail address ’some.really.long.username@somecompanywithalongdomainname.com’ with a comma instead of a dot before ‘com’, you’ll have to retype the whole thing all over again. Not very user-friendly. I like that the message is displayed in the field, but this is a very unfortunate side effect. Much better if you stuck the user-entered value in a variable and then put it back when you’re done displaying the message (e.g. when they put their focus in the field).

    April 25, 2012 at 8:15 pm
    Reply

  5. FidbecK

    Hi Joren I’ve sent you an email with a question regarding this tut.
    If you could please answer I’d be much appreciated, otherwise I can post my doubt here
    Thanks

    May 3, 2012 at 11:08 am
    Reply

  6. this was the most simplest validation script i ever used.. thanks for such a amazing script :)

    May 4, 2012 at 5:41 pm
    Reply

  7. Megan

    Great tutorial. Love the simplicity. Now if only there was a simple script for adding a background color to a required radio button it would be perfect. Anyone else come across this problem?

    June 20, 2012 at 3:10 pm
    Reply

  8. Rolypoly

    This seems simple enough, but the script calls for a mail.php. Where/how do we get the code of THAT page? Or am I missing something?

    July 6, 2012 at 8:03 am
    Reply

  9. Geoff

    This is a nice tutorial, but the e-mail validation is incorrect because it rejects perfectly valid e-mail addresses. Repeat after me: everything to the left of the “@” sign is called the local-part. The local-part can only be interpreted by the receiving site. Any attempt to “validate” it will inevitably result in errors. Read the RFCs on e-mail for more information.

    (In particular, the regex rejects addresses with plus signs in them, which are valid at lots of sites.)

    July 21, 2012 at 9:21 pm
    Reply

    • You are correct, that Regex bit does need updated (this is an old post). Any chance you know of a good one?

      July 21, 2012 at 9:36 pm
      Reply

    • Ok, I updated it to just validate that there’s an @ symbol, something before and something after, with a . in there. That should let everything through.

      August 3, 2012 at 10:43 am
      Reply

  10. Jessica

    This works in a .htm file, but it doesn’t in a .aspx file. Have you ran into that issue before? There is no change in the code except form ID, and I made sure to change that in the validation.js file. Any help is much appreciated.

    August 8, 2012 at 10:11 am
    Reply

  11. This is an amazing yet simplistic form validation. Simplicity is key.

    August 9, 2012 at 4:05 pm
    Reply

  12. Edward Witt

    Great script. It worked on a form I was working on. However, for some reason I can’t get it to work with prettyPhoto inline form pop up. prettyPhoto is a jQuery lightbox clone. Ever run into that issue?

    August 18, 2012 at 6:13 pm
    Reply

  13. This is great, simple fix. Just what I needed! Thanks so much!

    August 21, 2012 at 2:54 am
    Reply

  14. Brendon

    Very simple and easy to use. Will this check if a selection is made from a select list??? If so how do i set up the select list?

    September 11, 2012 at 12:03 pm
    Reply

    • Sadly I didn’t take into account selects when I wrote this. I think you can add a check to the javascript file using something like jQuery’s .is(’:checked’) to see if the user has made a choice.

      September 11, 2012 at 1:16 pm
      Reply

      • Brendon

        Thanks. I will give it a go but I am still very noobish at jquery. Any more help if you ever have time would be greatly appreciated

        September 12, 2012 at 6:35 pm

  15. sams

    check this site the best validator i ever saw

    http://learnwebscripts.com/flexible-jquery-form-validator

    September 21, 2012 at 9:14 am
    Reply

  16. Jay

    How would I go about validating whether or not a radio button or dropdown box option has been selected?

    November 2, 2012 at 5:28 pm
    Reply

  17. Gfunk

    Hi Guys

    I really need some urgent help. First of all nice little validion. Just one thing. Im trying to validate radio buttons. Its for gender, male or female. What jquery code can i add to the current code. Pls help

    December 13, 2012 at 8:33 am
    Reply

  18. Chris Baker

    Thanks! Question: I am relatively new to jQuery, but isn’t there a way to have jQuery search for all the elements that have the “needsFilled” class applied, rather than having to manually list them in the code (”required = ["name", "email", "message"];”)?

    January 8, 2013 at 12:25 pm
    Reply

    • You are correct sir. This post is pretty ancient, I have yet to get around to uploading it / directing people to a much more optimized version of this script.

      January 8, 2013 at 12:45 pm
      Reply

  19. hi,

    How can we validate select field in this file….?
    can you please send me the code….!!!

    Thanks

    March 2, 2013 at 2:25 am
    Reply

  20. Mal

    Thanks! Now how can I easily Google+ this? :)

    (Love the little street scape above the footer… very cute :)

    April 1, 2013 at 11:50 pm
    Reply

  21. This is really a very beneficial read for me, Need to admit you might be a single in the very best bloggers I ever saw.Thanks for posting this informative article.

    April 9, 2013 at 10:41 pm
    Reply

  22. Mat

    Thanks so much for sharing this. It’s really helpful

    April 30, 2013 at 12:19 pm
    Reply

  23. Does your site have a contact page? I’m having problems locating it but, I’d like to send you an email.

    I’ve got some recommendations for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it develop over time.

    May 2, 2013 at 8:34 pm
    Reply

  24. Shenu

    how i will give the error message outside the field ????
    plz help… thanx

    May 7, 2013 at 1:51 am
    Reply

Leave a Reply