Form Validation with Javascript and PHP
Form Validation with Javascript and PHP

Form Validation with Javascript and PHP

In this tutorial, we will show you how to create an attractive, pleasant to look form for your website, and then we will explain how to dynamically validate it using Javascript. The server-side validation with PHP will be covered too (to make everything 100% safe). This tutorial will help you to add more functionality to your forms that leads to better user experience and better website quality. You may also enhance your already existing forms with adding some fancy effects that are presented in this tutorial. Let us get started! Info: If you’d like to modify your existing forms, skip the HTML and CSS sections of this tutorial and go ahead to step number five. Otherwise, if you’re planning to create a new form, start reading since the beginning.

Concept

Let’s start with some brief explanation of what are we going to do. I’m sure that you have already seen a lots of different forms and you already noted that filling in some of them was much more convinient than filling in other ones. By and large, good ones were enhanced with additional scripts. We are going to cover several field types including standard input field, password field, repeat password field, email field, options list and few different js scripts. We hope that you’ll find here something useful for you. There are several things to consider before you creating forms:

  • Make sure that your form is as short as possible. People don’t like wasting time on filling in complex (and long) forms. They are likely to leave the page before they take any action. It’s better to require for less important information after user is already joined (preferably, only when you really need that information).
  • We want it to look neat and clean.
  • We want it to work seamlessly and without any strange behavior or errors.
  • We want to reduce number of fake submissions.
  • Project

    We’re going to start with HTML and then improve it with styles and scripts. At the end we’re going to use the following fields in my form (numbers of allowed chars are in the brackets):

    • Name (25)
    • Password (25)
    • Password Confirmation (25)
    • Email (50)
    • Gender (boolean)

    This is the plan: the best way to make each part is to start with HTML and then improve it by adding some style and scripts but you can actually start with preparing database (because you may have your own DB structure) or PHP script (step 12) and then, take care of the other steps. Tip: You always can increase maximum size of your text fields (it you need).

    Step 1 – HTML Forms

    Let’s prepare a new folder ‘templates’, where we will put all our html templates. Create a new document and name it ‘main_page.html’. Now we’re going to create a new HTML form and put it here. As you can see below, there are some comments referring to each part of my code, so I believe that at this point additional explanations are superfluous. I have also created a HTML table to align all the information. Here is the code:

    templates/main_page.html

    Things to note:
  • </pre>
    </li>
    	<li>
    <pre>01      <form action="index.php" method="post" id="form" onsubmit="return validate_all('results');">
    02      <table cellspacing="10">
    03
            <tr><td>Login</td><td><input type="text" name="login" maxlength="25" id="login" onKeyUp="updatelength('login', 'login_length')"><br /><div id="login_length"></div> </td></tr>
    04
            <tr><td>Password</td><td><input type="password" name="pass" maxlength="25" id="password" onKeyUp="updatelength('password', 'pass_length')"><div id="pass_result"></div><br /><div id="pass_length"></div></td></tr>
    05
            <tr><td>Confirm Password</td><td><input type="password" name="cpass" maxlength="25" id="c_password"></td></tr>
    06
            <tr><td>Gender</td><td><select name="gender"><option value="1">male</option><option value="0">female</option></select></td></tr>
    07
            <tr><td>Email</td><td><input type="text" name="email" maxlength="50" id="email" onKeyUp="updatelength('email', 'email_length')"><br /><div id="email_length"></div></td></tr>
    08
            <tr><td colspan="2"><input type="submit" name="submit" value="Register"></td></tr>
    09      </table>
    10       <h3 id="results"></h3>
    11      </form>
    
    • Don’t forget to name your text fields, otherwise you won’t be able to receive data from them later on.
    • Maxlength parameter reduces number of characters you can use in each text field.
    • Action, method and id parameters are required so place them into form tag.
    • You can make table border visible by placing border=”1″ in table tag if you want to actually see the table.

    Here’s the code of second page:

    templates/step2.html

<h2>{errors}</h2>
02  <form action="index.php" method="post">
03  <table cellspacing="10">
04   <input type="hidden" name="login" value="{login}">
05  <input type="hidden" name="pass" value="{pass}">
06  <input type="hidden" name="cpass" value="{cpass}">
07  <input type="hidden" name="gender" value="{gender}">
08  <input type="hidden" name="email" value="{email}">
09  <tr>
    <td><span>Verification code</span></td>
    <td><input name="vcode"></td><td>
     </td>
     </tr>
10  <tr>
    <td><span>Hint</span></td>
    <td><i>{vcode}</i></td><td>
    </td>
     </tr>
11   <tr> <td colspan="2"><input type="submit" name="submit" value="Register"></td></tr>
12   </table>
13    </form>
      

And – last one page:

templates/step3.html

1 <h1>Registration complete</h1>

Step 2 – Adding CSS

Now we have our HTML form but it does not look attractively yet. As you may have guessed it is time to add some CSS and make our form look a little better. Here is my example of green form definitions:

css/main.css

 


form {
02
    background-color: #555;
03
    display: block;
04
    padding: 15px;
05
}
06
input[type=text], input[type=password], input[type=submit] {
07
    -moz-border-radius: 2px;
08
    -ms-border-radius: 2px;
09
    -o-border-radius: 2px;
10
    -webkit-border-radius: 2px;
11
    border-radius: 2px;
12
}
13
input[type=text], input[type=password], select {
14
    background-color: rgb(246, 254, 231);
15
    border-color: rgb(180, 207, 94);
16
    border-style: solid;
17
    border-width: 1px;
18
    font-size: 16px;
19
    height: 25px;
20
    margin-right: 10px;
21
    width: 200px;
22
}
23
input[type=submit]{
24
    cursor: pointer;
25
    font-size: 16px;
26
    height: 35px;
27
    padding: 5px;
28
}
29
input.wrong {
30
    border-color: rgb(180, 207, 94);
31
    background-color: rgb(255, 183, 183);
32
}
33
input.correct {
34
    border-color: rgb(180, 207, 94);
35
    background-color: rgb(220, 251, 164);
36
}
37
#pass_result {
38
    float: right;
39
}

Classes are named according to their further function. For example .wrong class will be used when text field contains wrong informations and so on. Also you should now add class parameter to each text field and elements that should have some style. To do it place class=”class_name_here” to input tags whereclass_name_here is name of class defined between style tags (see example if you are new to adding classes to elements). Add only field class to each text field, rest will be used later. I advise to modify styles a little by choosing different colors and values so that they could fulfill your requirements.

Step 3 – Javascript

This step will be about dynamic elements and how to use Javascript to create and then apply them wherever you would like to. After observing what some sites do I’ve noticed that there are plenty of such scripts (which I’m going to present here) recently, especially on big companies/corporations sites and popular services so I think this really make users happier and encourage them to fill forms in. Look around and check out some sign up forms (Google.com, Yahoo.com and flickr.com, ebay.com… yes, dynamic forms are almost everywhere now). Some easy to do scripts can reduce number of unnecessary clicks and let users create account (or whatever you are making form for) more quickly than before, not to mention they look much more prettily and cool. There are various places to put the javascript code as it was with CSS. It can either be written inside the main_page.html file using a tag or put to the other file and then include this file to main_page.html. Both case will use the same code to put scripts to your document. I chose second option so make separated script file (js/script.js) for our main_page.html file.

Each function from further steps should be placed where I made comment so between.

Step 4 – Applying functions

This is very important step so read it carefully. Adding javascript functions to your HTML form elements should be easy because it is very similar to adding CSS classes to them. Also to make it easier I tried to create functions from further steps alike to each other so that you can apply them almost the same way but for sure I will add some sample files each step to show you how it is made and I will write a little explanation to them. Generally if you want to add function (let’s say updatelength() from Step 7 – Counter) to login field you should replace:

with:

1
<input type="text" name="login" maxlength="25" id="login" onKeyUp="updatelength('login', 'login_length')">










<div id="login_length"></div>











The only thing that has changed is onKeyUp=”updatelength(‘logid’, ‘login_length’)” was added. Well, if we add something like this to our input we will observe what function is returning outcome in div tag with id “login_length”.

Why?

Because updatelength() function starts like this “function updatelength(field, output){…” (Step 7 – Counter) and that means it requires two arguments which are ID OF TEXT FIELD IN HTML and ID OF DIV WHERE RESULT WILL BE. Now it is easy, isn’t it? :) Rest of functions are similar to this one so I hope it won’t be a problem to apply it. Each one needs almost same values as arguments.
Notes:

Step 5 – Counter

So, here goes first script to improve our sign up form. It can be used in many other cases like adding a comment or posting message somewhere so you can attach it to more than one form. It will count characters we typed and tells us how many more we can write to the end of field. Short code and useful thing:

1
function updatelength(field, output){
2
    curr_length = document.getElementById(field).value.length;
3
    field_mlen = document.getElementById(field).maxLength;
4
    document.getElementById(output).innerHTML = curr_length+'/'+field_mlen;
5
    return 1;
6
}

Once you have placed it, you can run it using method presented in previous step (also there is example of usage described). This script checks how many characters did you use (each time you use one) and how many are allowed by text field’s maxlength parameter, then it changes value between the div tags. There are 2 variables called ‘curr_length’ and ‘field_mlen’. First one gets and store number of characters you’ve typed (as I already wrote each time you type something in the field) and second one stores value of maxlength parameter of the field on which you are using this function. Then it simply shows both values with ‘/’ separator in the middle. Note:

  • I applied this script to every field

Step 6 – Password Strength

Now it will be something which will check for how strong the password is. Scripts like this are usually not very extended so here is the basic version of it:

01
function check_v_pass(field, output) {
02
    pass_buf_value = document.getElementById(field).value;
03
    pass_level = 0;
04
    if (pass_buf_value.match(/[a-z]/g)) {
05
        pass_level++;
06
    }
07
    if (pass_buf_value.match(/[A-Z]/g)) {
08
        pass_level++;
09
    }
10
    if (pass_buf_value.match(/[0-9]/g)) {
11
        pass_level++;
12
    }
13
    if (pass_buf_value.length < 5) { 14 if(pass_level >= 1) pass_level--;
15
    } else if (pass_buf_value.length >= 20) {
16
        pass_level++;
17
    }
18
    output_val = '';
19
    switch (pass_level) {
20
        case 1: output_val='Weak'; break;
21
        case 2: output_val='Normal'; break;
22
        case 3: output_val='Strong'; break;
23
        case 4: output_val='Very strong'; break;
24
        default: output_val='Very weak'; break;
25
    }
26
    if (document.getElementById(output).value != pass_level) {
27
        document.getElementById(output).value = pass_level;
28
        document.getElementById(output).innerHTML = output_val;
29
    }
30
    return 1;

As a ‘field’ argument we should put an ID of field to check and in ‘output’ goes place where the result will be shown. Of course DON’T TYPE IT HERE but when you are using this function (here you are only creating it) so replace values only when you write OnKeyUp=”… in your input :). Function also here contains two variables. First one called ‘pass_level’ contains current password strength and it is set to 0 by default because password field is empty at the beginning. Second variable named ‘pass_buf_value’contains current value of your password field. Below those two you can see some if()-s, they are looking for some characters that may increase password strength level and if one of them find anything it updates value of ‘pass_level’ variable by adding 1 to it. Of course rest of the script returns proper informations, it chooses right text depending on current ‘pass_level’ value. Apply this script to your password field.

Step 7 – Comparing passwords

Third script compare value from password field with value from confirm password field to make user sure, he typed exactly what he wanted. Characters here are not visible so to check if user did not make any mistakes we need two different fields and both has to contain same values when typing, only then form is filled correctly:

01
function compare_valid(field, field2) {
02
    fld_val = document.getElementById(field).value;
03
    fld2_val = document.getElementById(field2).value;
04
    if (fld_val == fld2_val) {
05
        update_css_class(field2, 2);
06
        p_valid_r = 1;
07
    } else {
08
        update_css_class(field2, 1);
09
        p_valid_r = 0;
10
    }
11
    return p_valid_r;
12
}

Guess how to use it? Only tip I will give you is that you should use it only on the compare password fieldand nowhere else. Well, this script as you can see arrogates values of 2 fields to two different variables called ‘fld_val’ and ‘fld2_val’. There is an if() construction below them which compares those two values and changes between 2 versions of style (green when everything is good and red when there are any errors).

Step 8 – Email verification

A bit more complicated script but usage is easy as always. Every email address must fulfill following criteria:
1. Must have some characters at the beginning (letters or numbers (and some less important))
2. Must have @ (at) character
3. Must have domain name
a) Must have first word
b) Must have . (dot) character
c) Must have second word
4. And in the event that somebody believe his email address contains big letters it must convert characters to small ones

01
function check_v_mail(field) {
02
    fld_value = document.getElementById(field).value;
03
    is_m_valid = 0;
04
    if (fld_value.indexOf('@') >= 1) {
05
        m_valid_dom = fld_value.substr(fld_value.indexOf('@')+1);
06
        if (m_valid_dom.indexOf('@') == -1) {
07
            if (m_valid_dom.indexOf('.') >= 1) {
08
                m_valid_dom_e = m_valid_dom.substr(m_valid_dom.indexOf('.')+1);
09
                if (m_valid_dom_e.length >= 1) {
10
                    is_m_valid = 1;
11
                }
12
            }
13
        }
14
    }
15
    if (is_m_valid) {
16
        update_css_class(field, 2);
17
        m_valid_r = 1;
18
    } else {
19
        update_css_class(field, 1);
20
        m_valid_r = 0;
21
    }
22
    return m_valid_r;
23
}

Place OnKeyUp=”… into input tag where email address is and create new div with adequate ID to make it work. This function basically looks up if the email address is typed correctly. First it arrogates value of the field to ‘fld_value’ variable to work with it. Everything is supervised by 4 if() constructions. They are step by step checking if there is @ symbol (1), then if it is on the second or further position (2). At the end if there is “dot” character after @ symbol (3) and finally if there are any characters before and after this “dot” (4). If any of if()-a find error it stops script and switches to red style wrong style of field. Those if()-s are a bit complicated as you can see but finally result is same as always, it chooses between green and red style and then shows it. Second part of this script is similar to switching between two options in already explained part so it should be clear for now.

Step 9 – Empty fields

Short function checking if there is more than 0 characters in our inputs. If there are empty spaces somewhere we can’t create new account:

01
function valid_length(field) {
02
    length_df = document.getElementById(field).value.length;
03
    if (length_df >= 1 && length_df <= document.getElementById(field).maxLength) {
04
        update_css_class(field, 2);
05
        ret_len = 1;
06
    } else {
07
        update_css_class(field, 1);
08
        ret_len = 0;
09
    }
10
    return ret_len;
11
}

Like usually here also we have to give a text field ID and ID of div where result of script should be as an arguments. Add this script to each field (except gender one). This one has only one interesting part to explain because rest should be clear for you already. I’m talking about this long if() construction in the third line. It first checks if value of the field has at least one character and than in its second part if it has no more than ‘max number’ of characters. Then it just changes between two options – right and wrong.

Step 10 – Coloring

This one is very short and only changes mode between two classes to make better visual effects. Classes must be defined in our CSS part of document (they are if you copied definitions from step 4). I called them wrong and correct:

1
function update_css_class(field, class_index) {
2
    if (class_index == 1) {
3
        class_s = 'wrong';
4
    } else if (class_index == 2) {
5
        class_s = 'correct';
6
    }
7
    document.getElementById(field).className = class_s;
8
    return 1;
9
}

As you may have already noticed this function is ran by other ones. Previous and further scripts puts arguments here. First argument is an ID of field you are currently working with and second is number 1 or 2. This numbers are being changed depending on actual field status to let then change its style to correct one. Let’s continue to next step.

Step 11 – Last Javascript verification

This is the last script using javascript. It calls out every function once more for sure and returns encountered errors or allows us to continue. It does not require refreshing whole page but check form quickly after pressing “Register”. That’s very important script and other ones were mostly make to let this one work:

01
function validate_all(output) {
02
    t1 = valid_length('login');
03
    t2 = valid_length('password');
04
    t3 = compare_valid('password', 'c_password');
05
    t4 = check_v_mail('email');
06
    t5 = check_v_pass('password', 'pass_result');
07
 
08
    errorlist = '';
09
    if (! t1) {
10
        errorlist += 'Login is too short/long<br />';
11
    }
12
    if (! t2) {
13
        errorlist += 'Password is too short/long<br />';
14
    }
15
    if (! t3) {
16
        errorlist += 'Passwords are not the same<br />';
17
    }
18
    if (! t4) {
19
        errorlist += 'Mail is wrong<br />';
20
    }
21
    if (errorlist) {
22
        document.getElementById(output).innerHTML = errorlist;
23
        return false;
24
    }
25
    return true;
26
}