- Home
- Registration
- Database Design
- Password Keeper
- MySQL and Excel
- Learn MySQL
- Learn SQL
- Learn PHP
- Learn C++
- Learn Java
- Learn Visual Basic
- Affordable Hosting
- Domain Name
- 301 Redirect
- Hosting Tips
- Monitor Site
- CPanel: Mail
- CPanel: MySQL
- CPanel: File Manager
- phpMyAdmin
- Authentication
- Display from file
- CSS Fixed Layout
- CSS Float Layout
- SEO tips
- Form Validation
- Miscellaneous
- Advertise here
- Site map
- LaptopForLess
- Geeks´ Stuff
- Nerds´ Stuff
- Remote Control Toys
JavaScript Form Validation
By Sergey Skudaev
![]()
![]()
![]()
![]()
![]()
In this example you will find a complete javascript code example of validation of fields on a form before the form is submitted. You can download that javascript code and use it with PHP code pages. Let us create a form with the following fields: First name, Last name, email, phone, date of birth.
CSS layout for PC and mobile device. $2.95
By S.Skudaev, (an eBay Excellent seller)
Contents:
1. How to install Pocket PC emulator on your Windows PC
2. Three columns layout CSS styles for regular PC browsers
3. One column layout CSS styles for mobile device

Pay via PayPal. You should not be concern about my web site security, because when you click the link, you will be redirected to PayPal site and it can be trusted. You will have your financial transaction with PayPal, not with me. So, please do not afraid to buy from my site. Credit cards are accepted. After payment is done, on the PayPal thank you page
Three columns layout template created in such a way that the middle column content coming first in the HTML code. This way, Google spider, while visiting your page, will see your main content first. Then the right and the left columns are placed.
In mobile device, web page has only one column. The same web page is used for regular browsers and a mobile device. It is very important because if you create two pages with the same content, Google will punish you for duplicate content.My tutorials are different from all other tutorials and books because I do not skip initial steps that a reader needed to start learning. Some times, you buy a book and start to read it. You understand everything from the point the author starts, but you do not know how to get to that starting point. I never miss the beginning!
<table align="center" width="90%" >
<tr><td>
<input type=text name=firstname size="10" >
</td></tr>
<tr><td>
<input type=text name=lastname size="10" >
</td></tr>
<tr><td>
<input type=text name=email size="10" >
</td></tr>
<tr><td>
<input type=text name=phone size="10" >
</td></tr>
<tr><td> <input type=text name=dob size="10" >
</td></tr>
<tr><td>
<input type=submit name=submit value="Add Person" size="10" >
</td></tr></table>
</form>
Before saving field values to the database, it is a good idea to check if the values are valid. It is easy to do with JavaScript
Usually, I use two js files. In one file I define functions for validation of each possible field. It is generic file that I include in every web page with a form. The second js file is form specific. It is different for each form depending on what kind of fields form has.
For example, if my form has only phone field, then in the specific js file I call only function that validate phone field. Another form may have date and phone then in form specific js file I call functions that validate date and phone fields.
In our example form has five fields and in form specific js file we will call functions for validation of every field.
Let us start from generic js file and define functions for validation of each field. The easiest function is for validation firstname and lastname fields, because it will only check if data was entered in the field. If the field is empty, then the user will see a message that the field is required.
function valid_required(field)
{
if(field=="")
{
return false;
}
return true;
}
If field parameter is empty the function will display a warning message:
"This field is required. Please enter data!"
and it will return "false", otherwise it will return "true" without any warning.
The alert is a built in JavaScript function that displays our message.
How to call this function? In form specific js file we create function "valForm()" and inside this function we will call the valid_required function and pass first name value to check if the user typed her first name:
function valForm()
{
if(!valid_required(document.myform.firstname.value))
{
alert("First name is required field!")
return false;
}
return true;
}
The code means: if function valid_required returns false then valForm() returns false, otherwise valForm() returns true.
Explanation: "document" object is our page. "myform" is a name of the form. Do you remember we typed <form name=myform…? The firstname is a field name and "firstname.value" is what user typed in the firstname text box or it is empty.
On the web page we cal valForm() function on submit event
If function valForm() returns false then the form will not be submitted. Besides, the function valid_required, which is called inside the valForm() function, will display a warning message. The user will see the message and hopefully will type her name.
OK. Let us write more complex function to validate phone number. For simplicity, assume that phone number should be entered without dashes.
function ValidPhone(aphone)
{
// declare valid variable as a string with all valid characters (digits from 0 to 9 )
var valid = "0123456789";
//if phone field is empty - display a warning and return false
if(aphone=="")
{
alert ("This field is required. Please enter phone number without dashes!")
return false
}
//if number of character in phone field is not equal 10 - display warning and return false
if(aphone.length !=10)
{
alert("Invalid phone number length! Please try again.")
return false
}
//check each character entered in the phone field
for (var i=0; i < aphone.length; i++)
{
//put in temp variable each character, one at a time.
temp = "" + aphone.substring(i, i+1);
//check index of a phone character in the "valid" variable.
// if temp contains a character which is not in "valid" variable,
//then valid.indexOf(temp) will be -1, otherwise it may be 0.1.2.3.4.5.6.7.8 or 9
if (valid.indexOf(temp) == "-1")
{
alert("Invalid characters in your phone. Please try again.")
return false;
}
}
//if all conditions are passed, then return true
return true
}
We have done with ValidPhone function
Let us write ValidDate function. It is similar to ValidPhone function
function ValidDate(datefield)
{
//if field is empty display - warning and return false
if(datefield=="")
{
alert("This field is required. Please enter date mm/dd/yyyy!")
return false;
}
//declare valid variable with all valid characters: digits from 0 to 9 and backslash
var valid = "0123456789/";
//declare variable for counting number of slashes
var slashcount = 0;
//checking date length. If it not equals 10 - display warning and return false
if (datefield.length!=10)
{
alert("Invalid date! The correct date format is like '01/01/2004'. Please try again.")
return false;
}
//check each character in the date field, one at a time
for (var i=0; i < datefield.length; i++)
{
temp = "" + datefield.substring(i, i+1);
//if character is backslash- count it
if (temp == "/")
slashcount++;
//if character in temp does not exist in valid character string, display warning
if (valid.indexOf(temp) == "-1")
{
alert("Invalid characters in your date. Please try again.")
return false;
}
//if number of slashes not equals 2 display warning
if (slashcount != 2)
{
alert("Invalid Date! The correct date format is like '01/01/2004'. Please try again.")
return false;
}
//check position of slashes in date string. It should be 2 and 5
// Because the first character position is 0 not one
if((datefield.charAt(2)!= '/')||( datefield.charAt(5) != '/'))
{
alert("Invalid date! The correct date format is like '01/01/2004'. Please try again.")
return false
}
}
return true
}
We have done with ValidDate function. Let us discuss function for validation email.
function EmailValid(aemail)
{
//if email field is empty - warning displays and return false
if(aemail=="")
{
alert ("This field is required. Please enter email myemail@mysite.com")
return false
}
//get email string length
len = aemail.length
//check position of @ character.
//it may be anywhere but not in the beginning or at the end of string.
if((aemail.charAt(1)=='@')||(aemail.charAt(1)=='.'))
alert ("Invalid email. Please enter email like myemail@mysite.com")
return false
if((aemail.charAt(len-2)=='@')||(aemail.charAt(len-2)=='.'))
alert ("Invalid email. Please enter email like myemail@mysite.com")
return false
//count number of @ occurrences and number of dot occurrences
count=0
dotcount=0
for (i=0; i< aemail.length; i++)
{
if(aemail.charAt(i)=='@')
count++
if(aemail.charAt(i)=='.')
dotcount++
}
//if @ or dot occurs not once display warning and return false
if((count !=1)||(dotcount !=1))
{
alert ("Invalid email. Please enter email like myemail@mysite.com")
return false
}
return true
}
Okey, we have done with all our functions for validation phone, date, email and required fields. Now we have to write form specific function, which will call all our functions to validate fields of our form.
function valForm()
{
//call valid_required function to check if field is not empty for first name
if(!valid_required(document.myform.firstname.value))
{
alert("First name is required field!")
return false
}
//call valid_required function to check if field is not empty for last name
if(!valid_required(document.myform.lastname.value))
{
alert("Last name is required field!")
return false
}
//call Emailvalid function to validate email entered by user
if(!EmailValid(document.myform.email.value))
{
return false
}
// call ValidPhone function to validate phone field value
if(!ValidPhone(document.myform.phone.value))
{
return false
}
//call ValidDate function to validate date field value
if(!ValidDate(document.myform.dob.value))
return false
// if everything passed - return true
return true
}
We have done. Save function definitions in form_validations.js file. The code for valForm() function with individual function calls save in myform.js file
Now include both js files in your web page header:
Source file: add_person_form.php
<html>
<head>
<title>Form validation Example </title>
<link rel="stylesheet" href="style.css">
<script language="JavaScript" src="form_validations.js"></script>
<script language="JavaScript" src="myform.js"></script>
</head>
<body>
<form name="myform" method="post" action="act_add_person.php" onSubmit="return valForm()">
<table align="center" width="90%" >
<tr><td>
<input type=text name=firstname size="10" >
</td></tr>
<tr><td>
<input type=text name=lastname size="10" >
</td></tr>
<tr><td>
<input type=text name=email size="10" >
</td></tr>
<tr><td>
<input type=text name=phone size="10" >
</td></tr>
<tr><td>
<input type=text name=dob size="10" >
</td></tr>
<tr><td>
<input type=submit name=submit value="Add Person" size="10" >
</td></tr></table>
</form>
<body>
<html>
Download file form_validation.js
Download file myform.js
Download file add_person_form.php
Download file act_add_person.php
Remove txt extension after downloading files.
* * *
If you do not like to read from screen you can download all contents of this web site as PDF file, print it out and read it seating in a comfortable chair.
To see the link, you have to be registered visitor. If I did not registered. Please register on my site .
Did you find information useful? Send to your friend a link to this page
Please rate the tutorial
| Comments | |
|---|---|
| Hi Sergey, How are you? I thank you and impressed with your help I am experimenting php form in my localdrive with wamp. This code in javascript, is works fine: if(jQuery.trim($(this).val()) == '') { var labelText = $(this).prev('label').text(); $(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>'); hasError = true;} However, I want to also show a message if user input only 1 character: Please enter your FUL | |
| Andrew C. B. 07-09-2009 | |
Web programming Tips