Javascript-jQuery

The simple Quick and small jquery form validation

This is a tutorial on how to write a live validation script for HTML form inputs using jQuery. 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.

01.#error {
02.    color:red;
03.    font-size:10px;
04.    display:none;
05.}
06..needsfilled {
07.    background:red;
08.    color:white;
09.}
1.<form action="mail.php" id="theform" name="theform" method="post">
2.    <p><label for="name">Name</label><br /><input id="name" type="text" value="" name="name" /></p>
3.    <p><label for="email">E-mail</label><br /><input id="email" type="text" value="" name="email" /></p>
4.    <p><label for="message">Message</label><br /><textarea id="message" rows="7" cols="30"  name="message"></textarea></p>
5.    <p><input class="submit" type="submit" name="submit" value="Submit Form" /></p>
6.    <p id="error">There were errors on the form, please make sure all fields are fill out correctly.</p>
7.</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.

1.// Place ID's of all required fields here.
2.required = ["name", "email", "message"];
3.// If using an ID other than #email or #error then replace it here
4.email = $("#email");
5.errornotice = $("#error");
6.// The text to show up within a field when it is incorrect
7.emptyerror = "Please fill out this field.";
8.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.

01.$("#theform").submit(function(){
02.    //Validate required fields
03.    for (i=0;i<required.length;i++) {
04.        var input = $('#'+required[i]);
05.        if ((input.val() == "") || (input.val() == emptyerror)) {
06.            input.addClass("needsfilled");
07.            input.val(emptyerror);
08.            errornotice.fadeIn(750);
09.        } else {
10.            input.removeClass("needsfilled");
11.        }
12.    }

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.

1.// Validate the e-mail.
2.if (!/^([a-zA-Z0-9_.-])[email protected](([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
3.    email.addClass("needsfilled");
4.    email.val(emailerror);
5.}

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 protected]”. 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.

1.    //if any inputs on the page have the class 'needsfilled' the form will not submit
2.    if ($(":input").hasClass("needsfilled")) {
3.        return false;
4.    } else {
5.        errornotice.hide();
6.        return true;
7.    }
8.});

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.

1.// Clears any fields in the form when the user clicks on them
2.$(":input").focus(function(){
3.   if ($(this).hasClass("needsfilled") ) {
4.        $(this).val("");
5.        $(this).removeClass("needsfilled");
6.   }
7.});

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!

Tags :