jQuery: Clientside Form validation
This is the first tutorial of many, which covers jQuery. My favorite javascript library. In this post we will cover how to create a simple form client-side validation script.
First we will create a simple form with two input fields, name and email. I will give it a little bit of styling to make it look more attractive than just a plain white form, but that is outside the scope of this tutorial (and actually it isn’t that attractive at all – don’t expect girls standing in line at least).
<div id="container"> <h1>jQuery Form Validation</h1> <form action="form"> <p> <label for="name">Name</label><input type="text" name="name" value="" id="name"/> </p> <p> <label for="email">Email</label><input type="text" name="email" value="" id="email"/> </p> <p><input type="submit" value="Submit form" id="submit"></p> </form> </div>
This gives the following form
The form used for validation
To be able to make the powers of jQuery come alive, we have to include it in our page. We take advantage of Google’s servers and include it from theirs
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
Now it’s time for the fun part! Let’s write that javascript that handles the validation. We can chose to include this from a separate file or simply add it directly in the page. For simplicity and since this is a small tutorial, I will just add it in a script tag on the page.
Let us add a function named form_validate() as the first thing. This is the function that has our validate logic. I like to name my functions with the element name first, so that it is easy for me to see where the specific function is used, instead of me guessing. This especially comes handy in large javascript files. But this is totally up to you :)
function form_validate() {
}
To get this function running at all, we need to include it in the $(document).ready(function(){ } which is run once the page is done loading. So lets create that as well in our script block in our page.
$(document).ready(function(){
form_validate();
});
To make sure this is working and getting run as intended, lets add a alert() to our form_validate()
function form_validate() {
alert("Yup! It's working");
}
$(document).ready(function(){
form_validate();
});
Once we confirm that that is working perfect. Let’s continue and add something to our form_validate function.
First we will bind an event to our submit-button. This is done by the following piece of javascript in our form_validate() function.
$("#submit").bind("click", function() { alert("Test"); return false; }
Again we add in an alert() to make sure that this works. If it for some reason doesn’t work, then make sure that you have added an id attribute to the submit-button (the # in front of submit, denotes that it looks after an id value on the page, like a css-selector) and that you have added the form_validate() function to the document-ready-function. The return false prevents the form from submitting and then reloading the page.
Lets delete that content for now and add something else.
$("#submit").bind("click", function() {
// Will get all inputs in form (3 inputs)
var allInputs = $(":input");
}
That will find all inputs on our page. Since this is a simple example, it is ok to write it like this. If we had a bigger page, we would probably like to stay within our form and we would then add an id attribute to the form itself and then use that together with the :input in the selector. Like this #formid:input. But now we just stick with :input for the sake of simplicity.
We then extend it further with the following line
$("#submit").bind("click", function() {
// Will get all inputs in form (3 inputs)
var allInputs = $(":input");
$(allInputs).each(function(i){
});
}
This loops through all of the inputs on the page. The next step is to add some more logic to check if the value in the inputs meet our criteria
$("#submit").bind("click", function() {
// Will get all inputs in form (3 inputs)
var allInputs = $(":input");
$(allInputs).each(function(i){
var value = $(this).attr("value");
var id = $(this).attr("id");
var element = $(this);
if(id == "email")
{
if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/))
{
element.attr("class","").addClass("invalid");
}
else
{
element.attr("class","").addClass("valid");
}
}
});
}
The above might look a bit complicated but it’s actually pretty straightforward once you get the idea.
We loop through all of the inputs. For each input in the form, we save the value in the value variable, id in the id variable and so on. This is simply done not to clutter up the javascript. We then do a check if the id equals email (if we are looking at the email form-field). If that is the case, we match the value against a simple email-validation regular expression and if it doesnt match, we add an “invalid”-class to our email input-field and if it matches we add a “valid”-class. This will show the user which fields fails and wich are ok. So let’s add the styling to the page:
<style type="text/css" media="screen">
.invalid {
border: 2px solid red;
}
.valid {
border: 2px solid green;
}
</style>
This will add a red border around the input field if it didn’t validate and a green if it did.
Let’s add the same functionality for the name field.
if(id == "name")
{
if(value == "")
{
element.attr("class","").addClass("invalid");
}
else
{
element.attr("class","").addClass("valid");
}
}
This gives the following result on submit
It gives an error because the email isn't correct
We are almost done. The only problem is, that the form won’t submit when the data is correct, cause it returns false. Let’s add a variable to the function
var error = false;
And let’s set that to true if there is an error. Both in the email and name conditions.
if(id == "name")
{
if(value == "")
{
error = true;
element.attr("class","").addClass("invalid");
}
else
{
error = false;
element.attr("class","").addClass("valid");
}
}
We will then add a if-statement at the bottom, to check if the variable is set.
if(!error)
{
return true;
}
else
{
alert("Form validation failed! Please correct the errors marked in red");
}
At the same time we show an alert when the form validation failed, so that the user know what those red lines around the input fields mean.
That’s it :)
The source can be found here.