MorkaLork Development

Interesting stuff I've picked up over the years...

Form validation

2009-10-16 10:20:42 | 1359 views | javascript form input validate validation

Server side or client side validation?


Well. Both actually. The reason you'll want client-side validation (javascript) is to enhance the experience for the visitor. Client-side validation is instant and allows you to point out errors easily on the form.
However, you'll want server side validation as well in order to protect your own application.

The client side validation will be a help to the user (pointing out what parts were incorrect and highlight them etc) while server side validation will be a help to the application (locate possible attacks, malicious code etc).


Is it hard?


No, not really. I'm not a javascript fan, in fact, I hate it. I use it only when I must, and form validation is one of those rare cases where I do use javascript to enhance the visit for my guests.
This article will show you an easy form validation script. There will be follow up articles on how to make your validation more complex (both regarding safety and visual design).


Where to start?


Well, let's start by making a form:

<form action="validateForm1.html" method="post" name="myForm" onsubmit="return validateForm();">
<table>
<tr>
<th>Name</th>
<td><input type="text" name="name" id="name" /></td>
<td><p id="nameError" class="error"></p></td>
</tr>
<tr>
<th>Email</th>
<td><input type="text" name="mail" id="mail" /></td>
<td><p id="mailError" class="error"></p></td>
</tr>
<tr>
<th>Age</th>
<td><input type="text" name="age" id="age" /></td>
<td><p id="ageError" class="error"></p></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form>


This is quite a normal registry form for something simple. We'll need a Name, an Age and an E-mail address. We also want to make sure that:


To do this, we will use javascript with a regex. Regular expression is not something I will teach in this article, so if you've never heard of it before or think it's some kind of dinosaur, please visit http://www.regular-expressions.info/.

The three regular expressions we will use will look like this:

var isNumeric = /^[0-9]+$/;
var isLetters = /^[a-zA-Z]+$/;
var isEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;


The first two are quite simple, the last one is a very general e-mail regex that will check the basics of an e-mail structure. It will however not check for ip domains and some other things, so if you want a more complex one, google it =).

We also gave each control in the form an id which we will use to fetch these controls in the javascript:

var nameControl = document.getElementById("name");
var mailControl = document.getElementById("mail");
var ageControl = document.getElementById("age");


As you could see in the form, we've also added a span to each control called error* which we will use to display an error message if something is wrong. We'll catch these spans as well in the javascript:

var nameError = document.getElementById("nameError");
var mailError = document.getElementById("mailError");
var ageError = document.getElementById("ageError");


The error handling will work in two steps, since every control will be checked twice. First we will check if the textbox is empty, then we will check it with a regular expression, so let's look at the name check:

if(nameControl.value == "")
nameError.innerHTML = " * Name is empty";
else if(nameControl.value.search(isLetters))
nameError.innerHTML = " * Name must only contain letters";
else
nameError.innerHTML = "";


First we check if the value of the control is nothing (""), if it is, we output a message that the control is empty. If it is not empty, we make a check if all characters are letters, and if not, output an error message that will explain why the check failed.
If not, we leave the error message empty. The reason for an empty error message is for consecutive checks where we might have already outputted an error message which no longer applies.

This is basically it, we make the same checks for the other two controls. All that is left is to see if there are any errors. If there aren't, we will post the form, otherwise not.
The check we make is quite simple, we look if there have been any error output:

if(nameError.innerHTML == "" && mailError.innerHTML == "" && ageError.innerHTML == "")
return true;
else
return false;


If the form has been successfully filled, it should now work. If there are any errors, this will be displayed to the guest.


The full code



<html>
<head>
<script type="text/javascript">
function validateForm() {

//Get the controls
var nameControl = document.getElementById("name");
var mailControl = document.getElementById("mail");
var ageControl = document.getElementById("age");
//Get the error spans
var nameError = document.getElementById("nameError");
var mailError = document.getElementById("mailError");
var ageError = document.getElementById("ageError");

//Create expressions
var isNumeric = /^[0-9]+$/;
var isLetters = /^[a-zA-Z]+$/;
var isEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

//Cheack each one and if it fails, set an appropriate error message

//If name is empty or invalid
if(nameControl.value == "")
nameError.innerHTML = " * Name is empty";
else if(nameControl.value.search(isLetters))
nameError.innerHTML = " * Name must only contain letters";
else
nameError.innerHTML = "";

//If mail is empty or invalid
if(mailControl.value == "")
mailError.innerHTML = " * Email is empty";
else if(mailControl.value.search(isEmail))
mailError.innerHTML = " * Email is not valid";
else
mailError.innerHTML = "";

//If age is empty or invalid
if(ageControl.value == "")
ageError.innerHTML = " * Age is empty";
else if(ageControl.value.search(isNumeric))
ageError.innerHTML = " * Age must only contain numbers";
else
ageError.innerHTML = "";

//If any errors occurred, return false, otherwise true
if(nameError.innerHTML == "" && mailError.innerHTML == "" && ageError.innerHTML == "")
return true;
else
return false;

};
</script>
<style type="text/css">
.error {
color: #ff0000;
font-weight: bold;
}
</style>
<title>A simple form validation example</title>
</head>

<body>
<form action="validateForm1.html" method="post" name="myForm" onsubmit="return validateForm();">
<table>
<tr>
<th>Name</th>
<td><input type="text" name="name" id="name" /></td>
<td><p id="nameError" class="error"></p></td>
</tr>
<tr>
<th>Email</th>
<td><input type="text" name="mail" id="mail" /></td>
<td><p id="mailError" class="error"></p></td>
</tr>
<tr>
<th>Age</th>
<td><input type="text" name="age" id="age" /></td>
<td><p id="ageError" class="error"></p></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form>
</body>

</html>


You can try it yourself here!


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.