Simple Form Validation with jQuery
02/04/2010To continue the series of tutorials I have planned, I'd like to stay on the jQuery train and go over some super simple form validation. All we're going to do here is take a very simple form, mark a field as "required" and check that it has been filled out before passing it on to the processing script. Form validation gets way more complex than this, involving regular expressions to ensure that values match certain patterns, input scrubbing to remove any unneeded info, and formatting to covert entered data to a format usable by what ever system you've developed. For now, we're gonna stick with the simple stuff.
In recent years, with the growth of Javascript frameworks like jQuery, Prototype, MooTools, etc., inline, client side validation has become far more popular than it was in the past. A slight note of caution, don't ever rely on client side validation alone. Always, always back up your validation with a server side validation process as well. If you intend to use user input in database interactions, it's very easy for those malicious folks out there to blow up your site with some shady submissions. Javascript validation is simply to improve the user experience.
All that being said, let's get into it.
Form Markup
As ususal, we always start with the basic markup. So, let's layout our form like so:
<form id="test-form" method="post" action="process_text.php"> <label for="email">Email: </label> <input type="text" name="email" class="required" id="email" /> <hr /> <label for="phone">Phone Number: </label> <input type="text" name="phone" id="phone" /> <hr /> <button type="submit">Validate Me!</button> </form>
What we've got here is an extremely simple form. The key things to notice is the class attributes of the <input> tags. We're utilizing the class property of our input fields to mark fields that are required. This way, we don't have to hard code anything in our validation function as far as naming specific fields and so on so we can reuse it for any form we need.
Capturing the Form Submission
Okay, now we're going to get into some jQuery. To validate this form, we need to intercept the submission of the form before the data gets sent to the page we've set in our action property of the form. jQuery does this by way of the submit() function (More Info). Like all the jQuery event methods, it can either initiate the form submission, or define a function to execute before the form is submitted. Like below:
$('#test-form').submit(validateForm);
What this does is tie the validateForm function to the submission event of the element with the id of text-form. Once that function is called, jQuery will, by default, continue on with the submission of the form. To stop that, all you have to do is return false from your handler function.
Validation
Okay, time for the heavy lifting. What we need to do is cycle through the various inputs within our form and, based on the flags we've set up in our class assignments, determine if they're what we're expecting. Here's the finished validateForm() function, we'll dissect it below.
function validateForm(){
var form = this,
fields = $(':input', form),
total = fields.length,
errors = [],
i;
for (i=0; i < total; i++){
// Get Current Field
var cur_field = $(fields[i]);
// Check required
if ($(cur_field).hasClass('required') && ! $(cur_field).val().length) {
errors.push($(cur_field).attr('id') + " is a required field.");
}
}
// If there are errors, display them and cancel the form submission
if (errors.length){
// Create a ul to display the error messages
var error_list = $("<ul></ul>").addClass('error-list');
for (i=0; i < errors.length; i++){
var new_li = $("<li></li>");
$(new_li).html(errors[i]);
$(new_li).appendTo(errors_list);
}
$(errors_list).insertBefore(form);
return false;
}
// Everything Passes, submit the form.
return true;
}
Don't let this be off putting. It looks more complex than it really is. To start, we're defining some variables:
var form = this,
fields = $(':input', form),
total = fields.length,
errors = [],
i, currentField;
The form variable is a reference back to the form that initiated the submit event. This is defined as form simply for clarity's sake. The fields variable is an array we're filling with all the user input fields in the form. The total variable is just the count of all the fields. errors is an empty array that will hold any error messages we need to output as we go along. Finally, i is our generic iterator for any loops we need to run through.
Now, we need to look at each field's value one by one and check to make sure it meets all it's requirements. To do this, we'll use a for loop.
for (i=0; i < total; i++){
// Get Current Field
var cur_field = $(fields[i]);
// Check required
if ($(cur_field).hasClass('required') && ! $(cur_field).val().length) {
errors.push($(cur_field).attr('id') + " is a required field.");
}
}
Essentially, we're cycling through every field in the form and passing it through a conditional statement to determine if it is, indeed, required and if it's value is longer than 0 characters. To do this, we use the jQuery function hasClass() which returns a boolean value of true if the element has the class passed in the function (it returns false if it doesn't). Then, to check that the field has been completed, we just check for the character length of the field value:
! $(currentField).val().length. You'll notice the use of an ! before we check for the length. The ! character in a conditional statement means "not", so if you read it aloud, it would read something like if currentField does not have a length, which is what we're looking for (I bet you knew that already).
The last part of the function checks to see if we encountered any errors. If we did, we're going to create a list of those error messages and prepend them to the form, then cancel the form submission action.If there weren't any errors, we'll get out of the way and let the submission pass. Here's the code again.
// If there are errors, display them and cancel the form submission
if (errors.length){
// Create a ul to display the error messages
var error_list = $("<ul></ul>").addClass('error-list');
for (i=0; i < errors.length; i++){
var new_li = $("<li></li>");
$(new_li).html(errors[i]);
$(new_li).appendTo(errors_list);
}
$(errors_list).insertBefore(form);
return false;
}
// Everything Passes, submit the form.
return true;
We start with a conditional the check if any errors have been inserted into the errors array. If they have, we're going to use jQuery to create an empty <ul> element. This is going to hold our error messages and be inserted at the top of the form. Next, we're cycling through the error messages, creating a new <li> for each one, inserting the error message, and appending it to our error list. Once we've populated our error list, we just need to stick it at the top of the form and return false to cancel the form submission.
If there are no errors we just return true and let the form do it's work.
Categories: Tutorials
Tags: Development, jQuery, HTML