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!

110 Comments
  1. Jim Bouschor says:

    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!

    • Robin John says:

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

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

      • Greenwood Man says:

        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.

      • pierre says:

        Hi,

        correct is

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

  2. Greenwood Man says:

    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.

  3. Sean says:

    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.

  4. Brandon says:

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

  5. FidbecK says:

    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

  6. xakbox says:

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

  7. Megan says:

    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?

  8. Rolypoly says:

    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?

  9. Geoff says:

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

  10. Jessica says:

    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.

  11. Linen says:

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

  12. Edward Witt says:

    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?

  13. Jasmyn says:

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

  14. Brendon says:

    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?

    • Joren Rapini says:

      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.

      • Brendon says:

        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

  15. Jay says:

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

  16. Gfunk says:

    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

  17. Chris Baker says:

    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"];”)?

  18. Surinder says:

    hi,

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

    Thanks

  19. Mal says:

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

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

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

  21. Mat says:

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

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

  23. Shenu says:

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

  24. Mohit Shah says:

    bro…i was too tensed for the form validation, specially while using jQuery,
    i tried a lot but it didn’t solved my problem,

    but your code works too fine for me..
    thank you soo much…

  25. chris says:

    Hi,

    Thanks for sharing this.
    I try to verify an SELECT option but can’t find the way to do it.
    Someone did modify a little bit this code to make it works ??

    Thanks in advance

    Chris

  26. RC says:

    Great script. Is there an update available to make it work for radio buttons and drop-downs? Thanks in advance..

    RC

  27. Ricky says:

    Wow, very simple and great script. This is what I looking for. But I need also URL input validation. How to make URL validation? Thanks.

  28. Parag says:

    Hey Joren!
    Made some small changes.
    Shaved off some of your js code. Added placeholder is place of value. Placeholder looks much cleaner.

    HTML:

    Joren Rapini Live Validation

    body, input, textarea {
    font-size:12px;
    line-height:18px;
    font-family:Verdana, Geneva, sans-serif;
    }
    input {width:200px; padding-left: 3px;}
    .submit {width:120px;}

    #error {
    color:rgb(228, 141, 141);
    font-size:10px;
    display:none;
    }

    .needsfilled {border: 1px solid rgb(228, 141, 141);}

    .placeholder-red:-moz-placeholder{color:rgb(228, 141, 141);}
    .placeholder-red::-moz-placeholder{color:rgb(228, 141, 141);}
    .placeholder-red:-ms-input-placeholder{color:rgb(228, 141, 141);}
    .placeholder-red::-webkit-input-placeholder{color:rgb(228, 141, 141);}

    Name
    E-mail
    Mobile
    Message

    There were errors on the form, please make sure all fields are fill out correctly.

    JS:
    /*
    Created 09/27/09
    Questions/Comments: jorenrapini@gmail.com
    COPYRIGHT NOTICE
    Copyright 2009 Joren Rapini
    */

    $(document).ready(function(){
    // Place ID’s of all required fields here.
    required = ["name", "email", "message", "mobile"];
    // If using an ID other than #email or #error then replace it here
    email = $(“#email”);
    mobile = $(“#mobile”);
    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.”;
    mobileerror = “Please enter a valid mobile.”;

    $(“#theform”).submit(function(){
    //Validate required fields
    for (i=0;i 9 && mobile.val().length < 13)) {
    mobile.addClass("needsfilled placeholder-red");
    mobile.attr('value', "");
    mobile.attr('placeholder', mobileerror);
    }
    //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;
    }
    });
    });

Leave a Reply