Improved Form Handling using JavaScript

By Leidago Noabeb

Forms, as we know, are an indispensible part of web development. IT is often at the forefront of collecting data from users. There are very few, if any, restrictions on what a user can enter or do with a form. Often you would want the user to see some kind of feedback when working with forms. For example, if user did not enter an email address correctly, you would want this to be known before the data is submitted to the server on its way to a data store.

Client-Side Validation

While client-side validation is often much faster and provides the user with a very good experience, it is important to note that client-side validation should NOT replace server-side validation. This is mainly because of security among other reasons and also because JavaScript can be turned off on some web browsers. This article will look at the following areas of form development:

  • Form Design
  • Form Validation
  • Error Message Display

Designing Your Form

This article also assumes basic knowledge of CSS and HTML. How you design your form plays a role in how easy you will be able to identify your form elements. Being able to identify these form elements makes it possible to manipulate those elements leading to form validation. Our form that we will be looking at will collect information about users that can easily be used in a user registration form and will be designed in XHTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Form Handling</title>
</head>
<body>
<h1>Improved Form Handling with JavaScript</h1>
<form action="" method="POST" onsubmit="return validate(this);">
<fieldset class="credentials">
<legend>Access Credentials</legend>
<table border="0">
  <tr>
    <td><label for="username" class="hover">Username</label></td>
    <td><input type="text" id="username" class="required text"/>*</td>
  </tr>
  <tr>
    <td><label for="password" class="hover">Password</label></td>
    <td><input type="password" id="password" class="required text"/>*</td>
  </tr>
  <tr>
    <td><label for="email">Email</label></td>
    <td><input type="text" id="email" class="required email text"/>*</td>
  </tr>
  </table>
  </fieldset>
  <fieldset>
<legend>Other Information</legend>
  <table border="0">
  <tr>
    <td width="59"><label for="name">Name</label></td>
    <td width="207"><input type="text" id="name" class="required text"/>*</td>
  </tr>
    <tr>
    <td><label for="phone">Phone</label></td>
    <td><input type="text" id="phone" class="phone text"/></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" value="Submit Form" class="submit"/></td>
  </tr>
  <tr>
    <td colspan="2">* = Required Field</td>
    </tr>
</table>

</fieldset>
</form>
</body>
</html>

Where's the CSS?

Now that we have the basic form designed, we can add some CSS on it. Below is an outline of the styles that we will be using on this form:

/* CSS Document */

form {

font-family: Arial;

font-size: 14px;

width: 300px;

}

fieldset {

border: 1px solid #CCC;

margin-bottom: 10px;

}

fieldset.login input {

width: 125px;

}

legend {

font-weight: bold;

font-size: 1.1em;

}

label {

display: block;

width: 60px;

text-align: right;

float: left;

padding-right: 10px;

margin: 5px 0;

}

input {

margin: 5px 0;

}

input.text {

padding: 0 0 0 3px;

width: 172px;

}

input.submit {

margin: 15px 0 0 70px;

}

.tooltip{

font-style:italic;

color:#666666;

font-size:9px;

}

.errormsg{

color:#FF0000;

font-size:9px;

font-weight:bold;

}

#errmsgbox{

border:dotted #FFCC66 1px;

background-color:#FFFFCC;

width:300px;

height:60px;

color:#FF0000;

font-size:15px;

font-weight:bold;

}

Here's what the form looks like on a web page:

Leidago

JavaScript for Form Validation

The primary reason for form validation is to make sure that the data entered by the user is exactly what is expected server-side. If a user enters his or her age as "ten" and not as "10" then it might crash the server-side software if not validated. Another advantage of using client-side validation is that users will basically have instantaneous feedback concerning their input, which can only help to improve the overall experience of entering information into the form. To start with we will check the that all required fields are filled in by verifying that a field is not left blank and where there are default values entered we will validate that as well. So our checks will cover three areas:

  • Blank fields - Check for blanks
  • type of data entered - Integer of letters or both
  • Format of data entered - Correct format for email addresses for example

To check for blanks, we create a function that will go through all the fields on the form to see if they contain any values, and show an appropriate error message:

function checkblanks(pform1){

if(pform1.username.value==""){

alert("Please enter a user name")

pform1.username.focus()

return false

}

if(pform1.password.value==""){

alert("Please enter a password")

pform1.password.focus()

return false

}

if(pform1.name.value==""){

alert("Please enter a name")

pform1.name.focus()

return false

}

if(pform1.email.value==""){

alert("Please enter a email")

pform1.email.focus()

return false

}

return true

}

The code above checks for blanks by accessing the form elements by name. Because of the design of our form we could also access these elements by their IDs. More specifically, the code checks the values property of the form elements if they contain any values. A alert dialog box pops up to notify the user of any blank fields.

The next code will validate the type of data that is entered and also checks that the correct number of charcters is included. JavaScript can handle a variety of data types including integers and strings. The main reason for checking data types is so that server side validation runs smoothly. In many instances, data captured in forms are posted to a database. This means that strings, integers and dates have to be in the correct format in order for it to be correctly stored in a database. Our password should be minimum four characters and maximum eight characters:

function checkpassword(pform1){

var str=pform1.password.value;

//check required fields

//password should be minimum 4 chars but not greater than 8

if ((str.length < 4) || (str.length > 8)) {

alert("Invalid password length.")

pform1.password.focus()

return false

}

}

The function above first captures the submitted password and stores it in a variable called "str":

var str=pform1.password.value;

then it counts the number of characters (using the length() function) in the password to see if it meets the set restriction relating to its character count:

if ((str.length < 4) || (str.length > 8))

If it does not pass the test then an alert message is shown to notify the user thereof:

alert("Invalid password length.")

To ensure that the password is not a number we use the isNAN() function like so:

if(!isNaN(str)){

alert="this is not a number";

pform1.password.focus()

return false

}

Email Address Verification With JavaScript

To verify that a submitted value is correctly formatted, we will use regular expressions. Things like email addresses (which we will be looking at),phone numbers and URLs all have fixed formats that can be validated using regular expressions. In many of the previous articles of this kind, to validate an email address authors simply looked for the "@" sign and a dot (.) in a text to make a valid email address. This is of course in efficient for several reasons. One of them is that by using the above validation logic, the following will validate as true:

leidago.noabeb@myAddress

Try sending an email to the above email address and you will notice that it will fail. With regular expressions pattern matching capabilities, you can easily remedy this problem. On our form we have both an email address field and a phone number field. So let's validate those:

function checkemailphone(pform1){

var email = pform1.email.value;

var phone = pform1.phone.value;

var cleanstr = phone.replace(/[().- ]/g, '');

var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;

if(!(validemail.test(email))){

alert("Invalid email address")

pform1.email.focus()

return false

}

//check phone number

if (isNaN(parseInt(cleanstr))) {

alert("The phone number contains unwanted characters.")

}

}

So what did we do here? First of all, we captured the two values for email and phone number that was sent from the form:

var email = pform1.email.value;

var phone = pform1.phone.value;

Then we declare a validemail pattern for the email address:

var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;

To understand the regular expression we will divide it into smaller parts, so that it makes sense:

/^[a-zA-Z0-9._-]+: Means that the email address must begin with alpha-numeric characters (both lowercase and uppercase characters are allowed). It may have periods, underscores and hyphens.

@: There must be a '@' symbol after initial characters.

[a-zA-Z0-9.-]+: After the '@' sign there must be some alpha-numeric characters. It can also contain period ('.') and and hyphens('-').

.: After the second group of characters there must be a period ('.'). This is to separate domain and subdomain names.

[a-zA-Z]{2,4}$/: Finally, the email address must end with two to four alphabets. Having a-z and A-Z means that both lowercase and uppercase letters are allowed.

{2,4} indicates the minimum and maximum number of characters. This will allow domain names with 2, 3 and 4 characters e.g.; na,us, tx, org, com, net, wxyz).

Now that you have some basic understanding of regular expressions, let's continue with the code:

We now need to compare the submitted email address against the "validemail" pattern that we defined earlier:

if(validemail.test(email)){

The "test()" property tries to match the submitted email against the pattern that we submitted. We simply notify the user if the test fails:

}else{

err.message="Invalid email";

err.field=pform1.email;

}

To validate a phone number, we must first clear out any unwanted characters. To achieve this We use regular expression and the replace () function. It will replace anything that we have placed in our pattern of unwanted characters with a empty string:

var cleanstr = phone.replace(/[().- ]/g, '');

Then we look at what we have left with the isNaN() function. This function checks if a given value is a number or not:

if (isNaN(parseInt(cleanstr))) {

alert("Invalid phone number.")

}

Error Message Display

So far all our validation code has been displaying error messages in a popup dialogue box. We are going to change that so that error messages are displayed more effectively. So, let's combine the previous functions that we have been using into one function called checkform():

function checkform(pform1){

var str=pform1.password.value;

var email = pform1.email.value;

var phone = pform1.phone.value;

var cleanstr = phone.replace(/[().- ]/g, '');

var err={};

var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;

//check required fields

//password should be minimum 4 chars but not greater than 8

if ((str.length < 4) || (str.length > 8)) {

err.message="Invalid password length";

err.field=pform1.password;

}

//validate email

if(validemail.test(mail)){

}else{

err.message="Invalid email";

err.field=pform1.email;

}

//check phone number

if (isNaN(parseInt(cleanstr))) {

err.message="Invalid phone number";

err.field=pform1.phone;

}

if(err.message)

{

document.getElementById('divError').innerHTML = err.message;

err.field.focus();

return false;

}

return true

}

The code above takes all the error messages step by step and then displays them in the divError tag that is displayed at the top of the form.

HTML, CSS and JavaScript for the Whole Web Page and Form

Below is the entire form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Form Handling</title>
<link href="formstyle.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript">

function checkform(pform1){
var str=pform1.password.value;
var email = pform1.email.value;
var phone = pform1.phone.value;
var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
var err={};
var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

//check required fields
//password should be minimum 4 chars but not greater than 8
if ((str.length < 4) || (str.length > 8)) {

err.message="Invalid password length";
err.field=pform1.password;
}

//validate email
if(!(validemail.test(email))){
err.message="Invalid email";
err.field=pform1.email;

}

//check phone number
if (isNaN(parseInt(cleanstr))) {
err.message="Invalid phone number";
err.field=pform1.phone;
}

if(err.message)
        {
               document.getElementById('divError').innerHTML = err.message;
                err.field.focus();
                return false;        
                
        }


return true
}
</script>

</head>
<body>
<h1>Improved Form Handling with JavaScript</h1>

<form action="" method="POST" onsubmit="return checkform(this);">

<div id="errmsgbox">

<div id="divError"></div>

</div>

<fieldset class="credentials">
<legend>Access Credentials</legend>

<table border="0">

  <tr>
    <td><label for="username" class="hover">Username</label></td>
    <td><input type="text" id="username" class="required text"/>
      <span class="style1">*</span></td>
  </tr>
  <tr>
    <td><label for="password" class="hover">Password</label></td>
    <td><input type="password" id="password" class="required text"/>
      <span class="style1">*</span><br />
      <span class="tooltip">Minimum four and maximum eight characters</span> </td>
  </tr>
  <tr>
    <td><label for="email">Email</label></td>
    <td><input type="text" id="email" class="required email text"/>
      <span class="style1">*</span></td>
  </tr>
  </table>
  </fieldset>
  <fieldset>
<legend>Other Information</legend>
  <table border="0">

  <tr>
    <td width="59"><label for="name">Name</label></td>
    <td width="207"><input type="text" id="name" class="required text"/>
      <span class="style1">*</span></td>
  </tr>
  <tr>
    <td><label for="phone">Phone</label></td>
    <td><input type="text" id="phone" class="phone text"/></td>
  </tr>
  <tr>
    
    <td colspan="2"><input type="submit" value="Submit Form" class="submit"/></td>
  </tr>
  <tr>
    <td colspan="2">* = Required Field</td>
    </tr>
</table>

</fieldset>
</form>
</body>
</html>

Conclusion

Using regular expressions you can also validate URLs and any other values that requires validation. The examples I used in the this article only cover some of the more common data capture form elements, so please feel free to experiment as much as possible.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date