Free Guides
Language Tutorials

JavaScript
Form & component validation
Javascript Form Validation
PHP Advance Form validation code
PHP form validation is a frequent requirement in many applications. Different type of php form validations is used based on the requirements but the process remains same. Let us start with a simple one and then go to the complex email validation using PHP regular expression.
Let us keep an input box and we will not allow any user to enter null data in it. So our form validation script will check for null entry and do the processing accordingly. Our main page where form is there is called form.php and let us posts the data to another page and name it as form_validate.php. We will check and validate the variables in form_validate.php page. Here is the simple html form.
<form method=post action=form_validate.php>
<input type=text name=userid>
<input type=text name=password>
<input type=submit value=Submit></form>
On submit of this form all entered variables will be available on form_validate.php page so let us go to form_validate.php page and read the variable and check if any value is there or not. Let us use one flag to check the status of the variables for form validation.
<?php
$flag="OK"; // This is the flag and we set
it to OK
$msg=""; // Initializing the message to hold the error
messages
if(strlen($userid) < 5){ // checking the length of the entered
userid and it must be more than 5 character in length
$msg=$msg."( Please enter user id more than 5 character length
)<BR>";
$flag="NOTOK"; //setting the flag to error flag.
}
User id
validation is over, now let us start password checking.
if(strlen($password) < 5 ){ // checking the length of the entered
password and it must be more than 5 character in length
$msg=$msg."( Please enter password of more than 5 character length
)<BR>";
$flag="NOTOK"; //setting the flag to error flag.
}
Now let us
check the flag and give message accordingly, if the flag is set to
OK then all validations is passed and we can proceed for the
database checking. If the flag is set to NOTOK then entries are not
ok so we have to display the messages. We also give one back button
for the user to go back and correct the entries.
if($flag <>"OK"){
echo "<center>$msg <br>
<input type='button' value='Retry' onClick='history.go(-1)'></center>";
}else{ // all entries are correct and let us proceed with the
database checking etc …
}
This is PHP form validation by using two simple text boxes. We have checked only the number of characters entered by the user. Now let us move one more step and go for form validation checking the type of entry. Say in userid field other than characters are not allowed. We will use same flag to set the status and append the message to the message variable.
if(ereg('[^A-Za-z]',
$userid)){
//Only lower or upper case letters allowed.
$msg=$msg."( Please use only alphabets a to z as userid )<BR>";
$flag="NOTOK"; //setting the flag to error flag.
}
Validation (checking ) of period button on submit of Form
Period buttons are used when the visitor has to
select one of the many options available. For example in a signup
form the visitor has to select the sex by clicking on Male or Female
selection. In different cases there can be more than two options
also. For example mode of payment can be any one of the options
saying cash, check, draft, credit card, or wire transfer. We can
select one of the options out of many choices. We can check or
validate the submission by checking any selection is made or not.
The form will not be submitted if no selection is made.
Please note that we will be using client side JavaScript validation
so if the user browser has disabled JavaScript then we can't detect
the status of the selection by the user and the form will simply
submit. For this reason many scripts use server side validations. In
server side validation the data has to go and return from server so
it takes time. JavaScript validation in client side is fast and we
also can detect the JavaScript setting of the browser and redirect
the visitor or give a warning message asking to enable JavaScript.
Validation (checking ) of checkbox selection on submit of Form
Check box is used to get user inputs within the
form. A group of checkbox is used or a single check box is used to
collect the options of the visitor. The difference in check box and
period button is the user can't select more than one option in case
of period buttons. In checkbox the user can give more than one
option. For example in a newsletter script you can ask the visitor
to select their interested areas. Here the user can give one or more
than one are as the area of interest. So all options are to be
stored or covered for the user. This way we can get more than one
option for a choice. Here we will try with one checkbox and in
another tutorial we will consider more than one checkbox.
In signup forms you will see one checkbox asking you to read the
term and condition of the site and the user must agree to this by
selecting a checkbox. On submit of the form the status of this
checkbox is checked and if not checked by the user then alert
message is displayed saying the user has to agree to the terms and
conditions.
The JavaScript code is kept within
the head tag of the page. See the validation
<script
type="text/javascript">
function validate(form) {
// Checking if at least one period button is selected. Or not.
if (!document.form1.sex[0].checked &&
!document.form1.sex[1].checked){
alert("Please Select Sex");
return false;}
if(!document.form1.agree.checked){alert("Please Read
the guidelines and check the box below");
return false; }
return true;
}
</script>
To display the period button and check box see the code below.
<table
border='0' width='50%' cellspacing='0' cellpadding='0' ><form
name=form1 method=post action=action_page.php onsubmit='return
validate(this)'><input type=hidden name=todo value=post>
<tr bgcolor='#ffffff'><td align=center ><font face='verdana'
size='2'><b>Sex</b><input type=radio name=sex value='male'>Male
</font><input type=radio name=sex value='female'><font face='verdana'
size='2'>Female</font></td></tr>
<tr><td align=center bgcolor='#f1f1f1'><font face='verdana'
size='2'><input type=checkbox name=agree value='yes'>I agree to
terms and conditions </td></tr>
<tr bgcolor='#ffffff'><td align=center ><input type=submit
value=Submit> <input type=reset value=Reset></td></tr>
</table></form>
Checkbox Array in a Form
Checkboxes can be used as arrays and the value can
be collected using JavaScript. We will be discussing client side
JavaScript and the collection of checkbox value. You can visit the
php section for checkbox array handling using PHP server side
scripting. We can create a group of checkbox by giving them the same
name and that will create an array and from it we can collect the
names of the check boxes for which it is checked.
Here are some commands we will be using to get the details of the
events or actions we perform.
document.form1.scripts.length
This gives us the length of the array or the number of elements
present in the array. If we know we are using 5 checkboxes then we
can directly use the number 5 but it is a good to use this as this
picks up all the checkboxes of the group without missing any thing.
Note that the word scripts in the document.form1.scripts.length
is the name of the array and same as the checkboxes name.
The JavaScript code is kept within the head tag
of the page.
<script
type="text/javascript">
function validate(form) {
// Checking if at least one period button is selected. Or not.
if (!document.form1.sex[0].checked &&
!document.form1.sex[1].checked){
alert("Please Select Sex"); return false;}
var total=""
for(var i=0; i < document.form1.scripts.length; i++){
if(document.form1.scripts[i].checked)
total +=document.form1.scripts[i].value + "\n"
}
if(total=="")
alert("select scripts") else
alert (total)
return false;
} </script>
To display the period button and checkboxes see the code below.
<table
border='0' width='50%' cellspacing='0' cellpadding='0' ><form
name=form1 method=post action=action_page.php onsubmit='return
validate(this)'><input type=hidden name=todo value=post>
<tr bgcolor='#ffffff'><td align=center ><font face='verdana'
size='2'><b>Sex</b><input type=radio name=sex value='male'>Male
</font><input type=radio name=sex value='female'><font face='verdana'
size='2'>Female</font></td></tr>
<tr><td align=center bgcolor='#f1f1f1'><font face='verdana'
size='2'><b>Scripts You know</b><input type=checkbox name=scripts
value='JavaScript'>JavaScript <input type=checkbox name=scripts
value='PHP'>PHP <input type=checkbox name=scripts value='HTML'>HTML
</td></tr>
<tr bgcolor='#ffffff'><td align=center ><input type=submit
value=Submit> <input type=reset value=Reset></td></tr>
</table></form>
Check or Uncheck all in a group of checkbox in JavaScript
If we have a series or a group of check boxes then
we can provide one button to check all the checkboxes at one go and
another button to uncheck all the checked buttons by using client
side JavaScript. This way the user in a single attempt can check or
uncheck all the buttons. Note that this is a client side JavaScript
feature so JavaScript execution is to be enabled in the client
browser.
There are different ways to achieve this result; we can keep two
buttons for this. One button will check all the checkboxes and other
button will uncheck all the buttons. The same result we can achieve
by using a single buttons also. We can also keep one checkbox to get
the same functionality. When we check the single checkbox we can
make all the checkboxes checked and by uncheck we can make all the
checkboxes uncheck( Inside mailbox of hotmail.com you can see this )
. Let us start with two buttons first. One for check all and
other for Uncheck all .
Here is the JavaScript function to be kept within the head tag
<!--
<!-- Begin
function CheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}
function UnCheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
// End -->
</script>
This is the HTML code to be kept inside the body tag.
<b>Scripts for Web design and programming</b><br>
<input type="checkbox" name="check_list" value="1">ASP<br>
<input type="checkbox" name="check_list" value="2">PHP<br>
<input type="checkbox" name="check_list" value="3">JavaScript<br>
<input type="checkbox" name="check_list" value="4">HTML<br>
<input type="checkbox" name="check_list" value="5">MySQL<br>
<input type="button" name="Check_All" value="Check All"
onClick="CheckAll(document.myform.check_list)">
<input type="button" name="Un_CheckAll" value="Uncheck All"
onClick="UnCheckAll(document.myform.check_list)">
Here is the code for single button. Here is the
single function we use inside our head tags.
<SCRIPT
LANGUAGE="JavaScript">
<!--
<!-- Begin
function Check(chk)
{
if(document.myform.Check_All.value=="Check All"){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
document.myform.Check_All.value="UnCheck All";
}else{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
document.myform.Check_All.value="Check All";
}
}
// End -->
</script>
Now the html part
<b>Scripts for Web design and programming</b><br>
<input type="checkbox" name="check_list" value="1">ASP<br>
<input type="checkbox" name="check_list" value="2">PHP<br>
<input type="checkbox" name="check_list" value="3">JavaScript<br>
<input type="checkbox" name="check_list" value="4">HTML<br>
<input type="checkbox" name="check_list" value="5">MySQL<br>
<input type="button" name="Check_All" value="Check All"
onClick="Check(document.myform.check_list)">
</form>
Here is the code for head part of the script
<!--
<!-- Begin
function Check(chk)
{
if(document.myform.Check_ctr.checked==true){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}else{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
}
// End -->
</script>
Here is the code for body part .
<form name="myform" action="checkboxes.asp"
method="post">
<b>Scripts for Web design and programming</b><br>
<input type="checkbox" name="check_list" value="1">ASP<br>
<input type="checkbox" name="check_list" value="2">PHP<br>
<input type="checkbox" name="check_list" value="3">JavaScript<br>
<input type="checkbox" name="check_list" value="4">HTML<br>
<input type="checkbox" name="check_list" value="5">MySQL<br>
<input type="checkbox" name="Check_ctr" value="yes"
onClick="Check(document.myform.check_list)"><b>Check Control</b>
</form>
Enable and disable of text box through a checkbox
We may need to enable or disable a text box based
on the input of the user by using disabled property of the element.
For example we have some choices for the visitor and one of the
options is Others. Once the visitor select the others options then (
only ) one text box will be enabled to allow the visitor to fill the
details.
Here is the demo of this. Click the checkbox to enable or disable
the text box.
We have used the body onload command to keep the
text area disabled while the page is loading.
The full code is here.
<head>
<title>(Type a title for your page here)</title>
<script language="JavaScript">
<!--
function enable_text(status)
{
status=!status;
document.f1.other_text.disabled = status;
}
//-->
</script>
</head>
<body onload=enable_text(false);>
<form name=f1 method=post>
<input type="checkbox" name=others onclick="enable_text(this.checked)" >Others
<input type=text name=other_text>
</form>
</body>
</html>
Adding options to List Box in client side Javascript
Options to a drop down list box can be added
dynamically using client side JavaScript. We will discuss a simple
way of adding options to a list. The process of adding can be
controlled based on different condition required. Depending on
conditions options can be removed also.
Here we will take care that the options are added on the page load ,
so by default the list box is pre populated when the page is
displayed. You can see the demo at the end of this page. The main
function creates a new OPTION object and assigns values and text
part of the option. Here is the function which collects the list box
name, value and text as inputs and then adds the option to the list
box. Here is the function
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
Note that each time the function is called, it adds a new option to
the list box. So we can add one option by calling the function once.
Like this.
addOption(document.drop_list.Month_list,”January”, “January”);
So this way we can create a drop down list box of all the months by
calling the function each time for a month. So with this now you can
easily create the list box. But we will add another step to this by
using one array of months. So from the array of months we will loop
through and add each month to the list box. Here is how to create
the array
var month = new
Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
So now once our array is ready with data, we will loop through the
array by using for loop and then call the addOption function using
the data of the array. Here is the code.
for (var
i=0; i < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);
}
You can see with this array we
will able to populate the drop down list box of months. Here is the
simple code for html body tag and the form with drop down list
<body bgcolor="#ffffff"
text="#000000" link="#0000ff" vlink="#800080"
alink="#ff0000" onLoad="addOption_list()";>
<FORM name="drop_list"
action="yourpage.php" method="POST" >
<SELECT NAME="Month_list">
<Option value="" >Month list</option>
</SELECT>
</form>
</body>
Removing options from a List Box in client side Javascript
We can remove the options from a list box by using
client side JavaScript. You can see the article explaining how to
add options to a list box using JavaScript. Here we will discuss on
how to remove option on selection and removing all the options in
one go. We will use different functions and connect them to buttons
to execute them. Here are some functions and there uses in removing
the options. You can see the demo of this program here.
While the page loads we will try to populate the list box by using
onload event of the body tag. The list box will be filled with data
at the time of display to the visitors. The detail on how to add
options to list box you can get here. So we will go to the next step
Removing all the options
To remove all the options from the list box we will loop through all
the elements of the list box and remove one by one. We will use for
loop to loop from 0 to selectbox.options.length-1. The total length
( or the number of elements ) of the array we can get by using
selectbox.options.length and to this we are subtracting 1 as the
first elements starts from 0 ( not from 1 ). Here is the function
function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}
The for loop will remove all the elements with the
value of i changing from last element of the array to first element
of the array.
Removing Selected Options
We can remove the options one by one or by selecting more than one
option and then by pressing the button. Here also we will use the
similar function like above but before deleting we will check if the
option is checked or not. selectbox.options[i].selected will return
true if the option is selected. This way we will check all the
elements of the list box and if they are checked then we will add
the command selectbox.options.remove(i); to remove that particular
option from the list box. Here is the function.
function
removeOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
if(selectbox.options[i].selected)
selectbox.remove(i);
}
}
Adding the options
There is a full tutorial on adding the options to list box. So here
is the function.
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
function
addOption_list(selectbox){
addOption(document.drop_list.SubCat, "One","One");
addOption(document.drop_list.SubCat, "Two","Two");
addOption(document.drop_list.SubCat, "Three","Three");
addOption(document.drop_list.SubCat, "Four","Four");
addOption(document.drop_list.SubCat, "Five","Five");
addOption(document.drop_list.SubCat, "Six","Six");
}
Now we will see how the select box with the form and buttons are
placed in the body are of the page. Each button is connected to one
function with on click event handler. See here
<FORM name="drop_list"
action="yourpage.php" method="POST" >
<SELECT id="SubCat" NAME="SubCat" MULTIPLE size=6 width=10>
</SELECT><br>
<input type=button onClick="removeOptions(SubCat)"; value='Remove
Selected'>
<input type=button onClick="removeAllOptions(SubCat)"; value='Remove
All'>
<input type=button onClick="addOption_list()"; value='Add All'>
</form>
Transferring options from one multiple selection boxes to other
We can transfer options from one selection box to
other by selecting one by one or at one go. The uses of such a type
of selection are you can select more than one options and it offers
a better picture than selecting a group of checkboxes. To get an
idea how the script works, see the demo at the end of this page. You
can download the page with this code also.
This tutorial explains on how to move elements from one list to
other, there are one more tutorial where the second list options are
dynamically added or generated based on the selection of the first
list.
You can see there are four main functions the page does and each is
connected to one button. All the buttons have onlick event handler
connected to one function. The page on load calls one function
adoption_all_list() through the body tag to populate the first drop
down box with default values. There are tutorials on adding elements
or options to a list box to know how the function works. There is
another tutorial on removing options from the list box. You must
read these two tutorials before reading this. So out of the four
buttons we will discuss the button which moves the selected options
from first list box to second list box. For other functions refer to
those adding and removing option tutorials.
The function we will discuss is addOption_list(),
it moves the selected options to the second list box. On execution
of this function it collects the elements selected, to do this a for
loop is used which loops through all the options of the first list
box. The line
for(i=document.drop_list.Category.options.length-1;i>=0;i--)
does that. While inside the loop we can get the status of any
element by checking selected event and it returns true if the
element is selected. Then we can use if condition to get the status.
if(document.drop_list.Category[i].selected)
So if it is selected then we have to execute two steps ( inside the
above if condition ) first we will add the option to second drop
down list and then remove it from first list. Here are the two
steps.
addOption(document.drop_list.SubCat,
document.drop_list.Category[i].value,
document.drop_list.Category[i].value);
removeOption(Category,i);
The first step uses addOption function to insert the option and the
second step uses removeOption function to remove that element from
fist list box.
Here is the full function code for moving elements from one drop
down to second drop down.
function addOption_list(){
for(i=document.drop_list.Category.options.length-1;i>=0;i--) {
var Category=document.drop_list.Category;
if(document.drop_list.Category[i].selected){
addOption(document.drop_list.SubCat,
document.drop_list.Category[i].value,
document.drop_list.Category[i].value);
removeOption(Category,i);
}
}
}
Here is the html code to display the drop down boxes and the
buttons.
<body onload="addOption_all_list()"
;="" alink="#ff0000" bgcolor="#ffffff" link="#0000ff" text="#000000"
vlink="#800080">
<form name="drop_list" action="yourpage.php" method="post">
<input onclick="addOption_all_list()" ;="" value="Add All"
type="button">
<select name="Category" multiple="multiple" size="7">
<option value="PHP">PHP</option>
<option value="ASP">ASP</option>
<option value="JavaScript">JavaScript</option>
<option value="HTML">HTML</option><option
value="Perl">Perl</option><option value="MySQL">MySQL</option></select>
<input onclick="addOption_list()" ;="" value="Move >"
type="button"> <input onclick="move_all_Option()" ;="" value="Move
All >>" type="button"> <select id="SubCat" name="SubCat"
multiple="multiple" size="7"></select><input onclick="removeAllOptions(SubCat)"
;="" value="Remove All" type="button">
</form>