Thursday, November 25, 2010

php file system functions

PHP Filesystem Functions

Following example shows you some useful functions in filesystem.


How to get the total size of a system disk drive in PHP?

$totalDiskSize= disk_total_space("C:");

echo $totalDiskSize.' Bytes';
echo ($totalDiskSize/1024).' Kb';
echo ($totalDiskSize/(1024*1024)).' MB';
echo ($totalDiskSize/(1024*1024*1024)).' GB';

How to get the free space of a drive in PHP?

$free_space=disk_free_space("C:");

$freeDsikSpace=diskfreespace("C:");
echo $freeDsikSpace.' Bytes';
echo ($freeDsikSpace/1024).' Kb';
echo ($freeDsikSpace/(1024*1024)).' MB';
echo ($freeDsikSpace/(1024*1024*1024)).' GB';

How to determine whether a file or directory exists using PHP?

$fileName="C:\autorun.inf";

if(file_exists($fileName)){
echo 'File exists';
}else{
echo 'File not exists';
}
  $folder_name="C:\\Program Files";
if(file_exists($fileName)){
echo 'Folder exists';
}else{
echo 'Folder does not exists';
}

Get information about a file in PHP .

1. How to get a size of a file?
 

$fileName='C:\\boot.ini';

if(file_exists($fileName)){
echo 'File size = '.filesize($fileName).' bytes';
}else{
echo 'File does not exists';
}

2. How to get last modified time of a file?
  $fileName='C:\\IO.SYS';
if(file_exists($fileName)){
echo 'Last modified time '.date('d/m/Y H:i:s',filemtime ($fileName));
}else{
echo 'File does not exists';
}
3. How to get last accessed time of a file?
 

$fileName='C:\\boot.ini';

if(file_exists($fileName)){
echo 'Last accessed time '.date('d/m/Y H:i:s',fileatime ($fileName));
}else{
echo 'File does not exists';
}

4. How to delete a file in PHP?
 

$fileName='C:\\jkl.jpg';

if(file_exists($fileName)){
if(unlink($fileName)){
echo $fileName.' has beed deleted';
}else{
echo 'Delete faild';
}
}else{
echo 'File does not exists';
}

     
 

How to rename a file or directory in PHP?

$old_file_name='C:\\abc.jpg';
$new_file_name='C:\\jkl.jpg';

if(file_exists($old_file_name)){
if(rename($old_file_name,$new_file_name)){
echo $old_file_name.' has beed renamed to '.$new_file_name;
}else{
echo 'Rename faild';
}
}else{
echo 'File does not exists';
}

How to copy a file in to another location in PHP?

$old_file_name='H:\projects\hexa\data\old.txt';
$new_file_name='H:\projects\hexa\data\new.txt';

if(file_exists($old_file_name)){
if(!file_exists($new_file_name)){
if(copy($old_file_name,$new_file_name)){
echo $old_file_name.' has beed copied to '.$new_file_name;
}else{
echo 'Faild to Copy';
}
}else{
echo 'Unable to copy, a file with the same name is already exists';
}
}else{
echo 'Source file does not exists';
}

How to delete a folder in PHP?

$folder_name='H:\projects\hexa\data';

if(file_exists($folder_name)){
if(unlink($folder_name)){
echo $folder_name.' has beed deleted';
}else{
echo 'Delete faild';
}
}else{
echo 'Folder does not exists';
}

 

$folder_name='H:\projects\hexa\data2';

if(file_exists($folder_name)){
if(rmdir($folder_name)){
echo $folder_name.' has beed deleted';
}else{
echo 'Delete faild';
}
}else{
echo 'Folder does not exists';
}

How to create a folder/directory in PHP

$folder_name='H:\projects\hexa\data';

if(!file_exists($folder_name)){
if(mkdir($folder_name,0777)){
echo $folder_name.' has beed created';
}else{
echo 'Unable to create folder';
}
}else{
echo 'Folder already exists';
}

How to create a simple text file in PHP

$fileName='H:\projects\hexa\data\test.txt';

if(!file_exists($fileName)){
$file = fopen($fileName, 'w');
fwrite($file, 'This is a simple text file');
fclose($file);
}else{
echo 'File already exists';
}


$file_name='H:\projects\hexa\data\test.txt';

if(file_exists($file_name)){
$new_content = "This is a new line\n";
file_put_contents($file_name, $new_content);

/*create a new file or overight the contents
of existing file. You can use FILE_APPEND flag to append new content to a existing file.*/

//file_put_contents($file_name, $new_content, FILE_APPEND);
}else{
echo 'File does not exists';
}

How to read a file in PHP

$fileName='H:\projects\hexa\data\test.txt';

if(file_exists($fileName)){
$handle = fopen($fileName, "r");
$contents = fread($handle, filesize($fileName));
fclose($handle);
echo $contents;
}else{
echo 'File does not exists';
}


$fileName='H:\projects\hexa\data\test.txt';

if(file_exists($fileName)){
$contents = file_get_contents ($fileName);
echo $contents;
}else{
echo 'File does not exists';
}






©-Copyright By Duminda Chamara    JavaScript Validation  

Monday, November 8, 2010

Change style property using JavaScript

How to change style properties using JavaScript ?

Following example shows you how to change style dynamically in JavaScript.
In some occasions you may want to change the appearance of html elements dynamically. You can use JavaScripts to do this. Using Javascript you can set these style attributes dynamically. The following example shows you how to change style properties using javascript.

This example shows you how to change style properties using JavaScript. You can test this by selecting style properties from Style Settings section. Your changes will appear here. Remember that some style properties may not work in some browsers. In such case please use another browser to test this example.

This example shows how to change,
  • Font Family
  • Font Size
  • Font Color
  • Text Decoration
  • Text Transformation
  • Background Color
  • Text Align
  • Letter Spacing
using Javascript.
Style Settings
Font Family :
Font Size
Font Color
Text Decoration
Text Transform
Background Color
Text Align
Letter Spacing


1. Change background color in JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.background = '#FCFCFC';

2. Change font family using JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.fontFamily = "Verdana, Arial, Helvetica, sans-serif";

3. Change font color in JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.color = '#ADADAD';

4. Change font size using JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.fontSize = '10px';

5. Change text alignment in JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.textAlign='center';//left,right,justify

6. Change text case using JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.textTransform='capitalize';//capitalize,lowercase,uppercase,none

7. Change text decoration in JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.textDecoration='underline'; //overline, line-through, blink, none

8. Change letter spacing using JavaScript.

html code

<p id='text-to-change'>Place your text here</p>

Javascript Code

document.getElementById("text-to-change").style.letterSpacing='2';;

©-Copyright By Duminda Chamara JavaScript Validation

Sunday, September 5, 2010

Validate form in JavaScript

How to validate a form in JavaScript ?

Following example shows you how to validate a form JavaScript.

It is a good practice validate form fields before you submit the from. Because there can be number of mistakes during the submission. Some users forget to fill all required fields and some are filled the form with errors. You can avoid these common errors using client side validation and server side validation. You must include server side validation in you code. Because there can be unexpected results during the program execution, when you are forget to validate user inputs or when user disabled the JavaScript on his browser.

If you validate user inputs before request send to the server, It is convenient to the users as well as to you. Because if you use javascript to validate the form the browser does not submit the form until user entered valid data. So no need to send submit the same form many times for a single task. Also it serves server resources too.

The following example shows you how to validate a simple web form using javascript.

User Registration

User Registration

* indicates required fields.
       
First Name *   
Last Name *    
Gender*    
Birthday *
   
 
Email Address*    
Country*    
Address Line 1*    
Address Line 2    
Address Line 3    
Postal Code *    
       
     


1. Example code for validate web form in JavaScript.

Javascript Code

<script type="text/javascript" language="javascript">

function show_terms_and_conditions(){
var popup= window.open('terms-and-conditions.html','Terms and conditions','width=350,height=190,left=412,top=284');
return false;
}

function validate_form(){
var error_count=0;
var bd_error_count=0;

if(!is_not_empty("firstName","e_firstName")){error_count++;}
if(!is_not_empty("lastName","e_lastName")){error_count++;}
if(!validate_dropdown("gender","e_gender",0)){error_count++;}
if(!validate_dropdown("b_year","e_b_day",bd_error_count)){bd_error_count++;error_count++;}
if(!validate_dropdown("b_month","e_b_day",bd_error_count)){bd_error_count++;error_count++;}
if(!validate_dropdown("b_day","e_b_day",bd_error_count)){bd_error_count++;error_count++;}
if(!is_valid_email("email_address","e_email_address")){error_count++;}
if(!validate_dropdown("country","e_country",0)){error_count++;}
if(!is_not_empty("address_line_1","e_address_line_1")){error_count++;}
if(!is_not_empty("postal_code","e_postal_code")){error_count++;}

if(error_count>0){return false;}
var agreed=document.getElementById("chk_terms_and_conditions");
if(agreed.checked==false){
alert("Please accept terms and conditions before proceed");
return false;
}
return true;
}

function validate_dropdown(field,error_container,e_count){
var selected_value=document.getElementById(field).value;
if(selected_value=="0"){
return display_notification_icon(error_container,true);
}else{
return display_notification_icon(error_container,(e_count>0?true:false));
}
}

function is_not_empty(field,error_container){
var textBox=document.getElementById(field);
if(textBox.value.replace(/\s+$/,"")==""){
return display_notification_icon(error_container,true);
}else{
return display_notification_icon(error_container,false);
}
}

function display_notification_icon(field,has_error){
if(has_error==true){
document.getElementById(field).innerHTML="<img src=\"images/error.gif\" width=\"16\" height=\"16\" border=\"0\" title=\"Please fill required fields\" />";
return false;
}else{
document.getElementById(field).innerHTML="";
return true;
}
}

function is_valid_email(field,error_container){
if(is_not_empty(field,error_container)==true){
var emailAddress=document.getElementById(field);
var regExEmail=/^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
if(!regExEmail.test(emailAddress.value)){
return display_notification_icon(error_container,true);
}else{
return display_notification_icon(error_container,false);
}
}else{
return true;
}
}


</script>

HTML Code

<html><head><title>How to validate a form in javascript</title></head><body>
<form id="validate-form-using-javascript" name="validate-form-using-javascript" method="post" action="" onsubmit="javascript: return validate_form();" >
<table border="0" align="center">
<tr>
<td colspan="4"><h4>User Registration </h4></td>
</tr>
<tr>
<td colspan="4" align="right">* indicates required fields. </td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>First Name * </td>
<td><label>
<input name="firstName" type="text" id="firstName" size="30" class="html_element_border" onblur="javascript:is_not_empty('firstName','e_firstName');"/>
</label></td>
<td>&nbsp;&nbsp;</td>
<td id="e_firstName"></td>
</tr>
<tr>
<td>Last Name * </td>
<td><label>
<input name="lastName" type="text" id="lastName" size="30" class="html_element_border" onblur="is_not_empty('lastName','e_lastName')" />
</label></td>
<td>&nbsp;</td>
<td id="e_lastName">&nbsp;</td>
</tr>
<tr>
<td>Gender*</td>
<td><label>
<select name="gender" id="gender" class="html_element_border" onblur="javascript:validate_dropdown('gender','e_gender',0);">
<option value="0">--Select--</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</label></td>
<td>&nbsp;</td>
<td id="e_gender">&nbsp;</td>
</tr>
<tr>
<td>Birthday * </td>
<td><table border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
<td id="year_drop_down"><select name="b_year" id="b_year" class="html_element_border" onblur="javascript:validate_dropdown('b_year','e_b_day',0);">
<option value="0" selected="selected">Year</option><option value="1980">1980</option><option value="1981">1981</option><option value="1982">1982</option><option value="1983">1983</option><option value="1984">1984</option><option value="1985">1985</option><option value="1986">1986</option><option value="1987">1987</option><option value="1988">1988</option><option value="1989">1989</option><option value="1990">1990</option><option value="1991">1991</option><option value="1992">1992</option>
</select></td>
<td>&nbsp;</td>
<td><select name="b_month" id="b_month" class="html_element_border" onblur="javascript:validate_dropdown('b_month','e_b_day',0);">
<option value="0" selected="selected">Month</option>
<option value="1">Jan</option><option value="2">Feb</option><option value="3">Mar</option><option value="4">Apr</option><option value="5">May</option><option value="6">Jun</option><option value="7">Jul</option><option value="8">Aug</option><option value="9">Sep</option><option value="10">Oct</option><option value="11">Nov</option><option value="12">Dec</option>
</select></td>
<td>&nbsp;</td>
<td><select name="b_day" id="b_day" class="html_element_border" onblur="javascript:validate_dropdown('b_day','e_b_day',0);">
<option value="0" selected="selected">Day</option>
<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option>
</select></td>
</tr>
</table></td>
<td>&nbsp;</td>
<td id="e_b_day"></td>
</tr>
<tr>
<td>Email Address* </td>
<td><label>
<input name="email_address" type="text" id="email_address" size="30" class="html_element_border" onblur="javascript:is_valid_email('email_address','e_email_address');"/>
</label></td>
<td>&nbsp;</td>
<td id="e_email_address">&nbsp;</td>
</tr>
<tr>
<td>Country*</td>
<td><label>
<select name="country" id="country" style="width:150px;" class="html_element_border" onblur="javascript:validate_dropdown('country','e_country',0);">
<option value="0" selected="selected">Country</option><option value="IN">India</option><option value="LK">Sri Lanka</option><option value="GB">United Kingdom</option><option value="US">United States</option>
</select>
</label></td>
<td>&nbsp;</td>
<td id="e_country">&nbsp;</td>
</tr>
<tr>
<td>Address Line 1* </td>
<td><input name="address_line_1" type="text" id="address_line_1" size="30" class="html_element_border" onblur="javascript:is_not_empty('address_line_1','e_address_line_1');"/></td>
<td>&nbsp;</td>
<td id="e_address_line_1">&nbsp;</td>
</tr>
<tr>
<td>Address Line 2 </td>
<td><label>
<input name="address_line_2" type="text" id="address_line_2" size="30" class="html_element_border"/>
</label></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Address Line 3 </td>
<td><label>
<input name="address_line_3" type="text" id="address_line_3" size="30" class="html_element_border"/>
</label></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr><tr>
<td>Postal Code * </td>
<td><label>
<input name="postal_code" type="text" id="postal_code" class="html_element_border" onblur="javascript:is_not_empty('postal_code','e_postal_code');"/>
</label></td>
<td>&nbsp;</td>
<td id="e_postal_code">&nbsp;</td>
</tr>
<tr>
<td colspan="4" align="right"><label>
<input name="chk_terms_and_conditions" type="checkbox" id="chk_terms_and_conditions" value="1" class="html_element_border"/>
I accept <a href="javascript:void(0);" onclick="javascript:show_terms_and_conditions();">terms</a> and conditions. </label></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><label>
<input type="submit" name="Submit" value="Register" class="html_element_border"/>
</label></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</form></body></html>

 


©-Copyright By Duminda Chamara   JavaScript Validation  

Sunday, June 13, 2010

How to create xml file in php


How to create XML file in PHP?

Following example shows how to Create a XML file in PHP.

XML (Extensible Markup Language) file describes structured data in plain text based on tags under the standards of W3C. XML files make the data highly portable. So it can be use to transfer data between wide variety of applications. As an example you can make a connection between PHP and Flash using a xml file easily. XML is very useful to transfer data over the Internet. You can define any tag in a xml file. There should be starting tag and corresponding closing tag.

In PHP The DOM extension allows you to operate on XML documents through the DOM API. The following example describes how to create a simple xml file using DOM extensions. Here you can create a xml file in very few steps.

$dom = new DOMDocument(); // Represents an entire XML document (the root of the document tree)

After initializing the xml document you can set the document encoding and the xml version as follows.

$dom->encoding = 'utf-8';//set the document encoding
$dom->xmlVersion = '1.0';//set xml version

You can create the xml document with nice indentation. This is important when you reading the document.

$dom->formatOutput = true;//Nicely formats output with indentation and extra space
$dom->xmlStandalone = true; //Whether or not the document is standalone

Creating and adding the nodes to the XML file

$root = $dom->createElement('Root');//Creates the root element of the xml file
$node=$dom->createElement('Child_1');//Create a child node
$child_node_1=$dom->createElement('FirstName','Duminda');//Create child element
$node->appendChild($child_node_1);//append child element to the node
$root->appendChild($node);
$dom->appendChild($root);//append the root node
$dom->save('test.xml');//save the xml file

Adding attributes to the nodes of the XML file

$node=$dom->createElement('User');//create an element
$attr_user_id = new DOMAttr('user_id', '1020'); //Create an attribute
$node->setAttributeNode($attr_user_id);//set created attribute to the node

Adding CDATA to the XML file

$node=$dom->createElement('Address');//create a child node
$cdata_node = $dom->createCDATASection('type your address here ');//create a CDATA Section
$node->appendChild($cdata_node); //append CDATA Section to the node

Adding comments to the XML file

$comment = $dom->createComment('this is a test comment');//create a comment
$comment->appendData('add your custom text');//add more comment
$dom->appendChild($comment);//Add some comment to the xml file



Demo Create XML file in PHP
First Name
Last Name
Status
Address
Age
Email Address
Comment

1. Example code for create XML document using PHP.

<?php
$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$dom->xmlStandalone = true;
$xml_file_name='test.xml';
$root = $dom->createElement('Users');

$user_node=$dom->createElement('User');
$attr_user_id = new DOMAttr('user_id', '1020');
$user_node->setAttributeNode($attr_user_id);

$child_node_first_name=$dom->createElement('FirstName','Duminda');
$user_node->appendChild($child_node_first_name);
$child_node_last_name=$dom->createElement('LastName','Chamara');
$user_node->appendChild($child_node_last_name);

$child_node_email_address=$dom->createElement('EmailAddress','abc@gmail.com');
$user_node->appendChild($child_node_email_address);

$child_node_address=$dom->createElement('Address');
$cdata_node = $dom->createCDATASection('Duminda Chamara,
80062,
Galle,
SriLanka.');
$child_node_address->appendChild($cdata_node);
$user_node->appendChild($child_node_address);

$comment = $dom->createComment('this is a test comment');
$comment->appendData('add your custom text');
$dom->appendChild($comment);

$child_node_age=$dom->createElement('Age','12');
$attr = new DOMAttr('married', 'false');
$child_node_age->setAttributeNode($attr);
$user_node->appendChild($child_node_age);

$root->appendChild($user_node);
$dom->appendChild($root);
$dom->save($xml_file_name);
?>
Output
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--this is a test comment add your custom text-->
<Users>
<User user_id="1020">
<FirstName>Duminda</FirstName>
<LastName>Chamara</LastName>
<EmailAddress>abc@gmail.com</EmailAddress>
<Address><![CDATA[H.H.D.Chamara,
80062,
Galle,
SriLanka.]]></Address>
<Age married="false">12</Age>
</User>
</Users>

©-Copyright By Duminda Chamara    

Sunday, May 30, 2010

how to validate textbox using javascript


How to validate text box/textarea in Java Script?



Following example shows you how to validate text box or textarea in your web application

When filling forms, you may have seen there are some required fields to fill before you submit the form. If you are forget to fill such a field, you will be asked to fill that field to complete the process. Most of web application validate these fields as client side validation. That means they use JavaScript to validate user inputs. As an example there are two text boxes in your form called first name and last name, So you want that user to fill these fields, before they submit the form. Here is an example how to write validation script for that.


Also you can use input data validation to force user to enter appropriate data type. For a example if there is a text field in the form to enter the users age. So that the age should be non-negative number and most occasions it is less than 100. So you need to check if the user has entered the correct integer value for age field, that means check is it a number. Keep it mind to limit the user inputs to specific number of characters. You can use the attribute maxlength to limit the input characters. In most cases when you prompt for age as an input you can set maxlength to 2. You can do these validation events such as onclick, mouse over, on change, etc.

Note: You can select the error display method using provided drop down.


1. Validate textbox when user clicks on submit button

Example : This example describes you how to validate first name and last name. There are five error display options for you. Select your preferred method to validate your text box.

Syntax: <input name="Button" type="button" value="Submit" onclick="javascript:validate_textbox1(this.form);" />


onclick event of the button
First Name 
Last Name 
Error Display Type

Copy and paste bellow code for validate textbox

<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

function validate_textbox1(e) {

var t = parseInt(e["err_msg_type"].value);

if(isEmptyTextBox(e["firstName"], "Please enter First Name", t, "first_name_info")) {

return false

}

if(isEmptyTextBox(e["lastName"], "Please enter Latst Name", t, "last_name_info")) {

return false

}

return true

}

function isEmptyTextBox(e, t, n, r) {

var i = document.getElementById(r);

if(e.value.replace(/\s+$/, "") == "") {

i.className = ""

switch(n) {

case 0:

{

i.innerHTML = "";

alert(t)

}

break;

case 1:

{

i.innerHTML = t

}

break;

case 2:

{

i.innerHTML = "";

e.className = "err_tb1"

}

break;

case 3:

{

i.innerHTML = "";

e.className = "err_tb2"

}

break;

case 4:

{

i.innerHTML = "*";

e.className = "tb"

}

break;

case 5:

{

i.innerHTML = "&nbsp;&nbsp;&nbsp;";

i.className = "custom_error"

}

break

}

e.value = "";

e.focus();

return true

}

else {

if(n == 5) {

i.innerHTML = "&nbsp;&nbsp;&n";

i.className = "error_free"

}

else {

i.innerHTML = "";

i.className = ""

}

e.className = "tb";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_0" name="text_box_validation_0" action="#" method="post">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">onclick method of the button</td>

</tr>

<tr>

<td align="right">First Name</td>

<td>

<input name="firstName" type="text" class="tb" id="firstName" maxlength="50" />

<label id="first_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Last Name</td>

<td>

<input name="lastName" type="text" class="tb" id="lastName" maxlength="50" />

<label id="last_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td></td>

<td>

<input name="Button" type="button" value="Submit" onclick="javascript:validate_textbox1(this.form);" />

</td>

<td></td>

</tr>

<tr>

<td align="right">Error Display Type</td>

<td colspan="2"><select name="err_msg_type" id="err_msg_type">

<option value="0">Alert box</option>

<option value="1">Text message</option>

<option value="2">Change textbox border color</option>

<option value="3">Change textbox background color</option>

<option value="4">Display Star</option>

<option value="5">Custom Style</option>

</select></td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>

</tr>

</tbody>

</table>

</form>

</body>

</html>




2. Validate textbox - onblur method of the textbox

Example : This example explains you how to set validation for textbox or textare as onblur event of the element.

Syntax: <input name="lastName2" type="text" class="tb" id="lastName2" maxlength="50" onBlur="javascript:validate_textbox2(this,'Please enter Last Name','last_name_info2');" />

onblur event of the textarea or textbox
First Name 
Last Name 
Error Display Type

Copy and paste bellow code for validate textbox


<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

function validate_textbox2(text_box,message,lbl) {

var t = parseInt(document.getElementById("err_msg_type").value);

if(isEmptyTextBox2(text_box,message, t, lbl)) {

return false

}

return true

}

function isEmptyTextBox2(e, t, n, r) {

var i = document.getElementById(r);

if(e.value.replace(/\s+$/, "") == "") {

i.className = ""

switch(n) {

case 0:

{

i.innerHTML = "";

alert(t)

}

break;

case 1:

{

i.innerHTML = t

}

break;

case 2:

{

i.innerHTML = "";

e.className = "err_tb1"

}

break;

case 3:

{

i.innerHTML = "";

e.className = "err_tb2"

}

break;

case 4:

{

i.innerHTML = "*";

e.className = "tb"

}

break;

case 5:

{

i.innerHTML = "&nbsp;&nbsp;&nbsp;";

i.className = "custom_error"

}

break

}

e.value = "";

e.focus();

return true

}

else {

if(n == 5) {

i.innerHTML = "&nbsp;&nbsp;&nbsp;";

i.className = "error_free"

}

else {

i.innerHTML = "";

i.className = ""

}

e.className = "tb";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_1" name="text_box_validation_1" action="#" method="post">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">onclick method of the button</td>

</tr>

<tr>

<td align="right">First Name</td>

<td>

<input name="firstName" type="text" class="tb" id="firstName" maxlength="50" onBlur="javascript:validate_textbox2(this,'Please enter First Name','first_name_info2');" />

<label id="first_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Last Name</td>

<td>

<input name="lastName" type="text" class="tb" id="lastName" maxlength="50" onBlur="javascript:validate_textbox2(this,'Please enter Last Name','last_name_info2');" />

<label id="last_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<!--<tr>

<td></td>

<td>

<input name="Button" type="button" value="Submit"/>

</td>

<td></td>

</tr>-->

<tr>

<td align="right">Error Display Type</td>

<td colspan="2"><select name="err_msg_type" id="err_msg_type">

<option value="0">Alert box</option>

<option value="1">Text message</option>

<option value="2">Change textbox border color</option>

<option value="3">Change textbox background color</option>

<option value="4">Display Star</option>

<option value="5" selected>Custom Style</option>

</select></td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>

</tr>

</tbody>

</table>

</form>

</body>

</html>



3. Validate user name and password - onsubmit event of the form

This code sample shows you how to validate textfield at the onsubmit event of the form. If user forgot to enter values for required fields, He will be prompt to enter them before submit the form.

Syntax: <form id="text_box_validation_3" name="text_box_validation_3" action="#" method="post" onSubmit="javascript:return validate_login();">

onsubmit event of the form
User Name 
Password 
  
Copy and paste bellow code for validate textbox


<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

function validate_login()

{

var e = 0;

if(isEmpty("user_name", "Please enter User Name", "user_name_info"))

{

e++

}

if(isEmpty("password", "Please enter Password", "password_info"))

{

e++

}

if(e > 0)

{

alert("Please fill login details");

return false

}

else

{

return true

}

}

function isEmpty(e, t, n)

{

var r = document.getElementById(e);

var n = document.getElementById(n);

if(r.value.replace(/\s+$/, "") == "")

{

n.innerHTML = t;

r.value = "";

r.focus();

return true

}

else

{

n.innerHTML = "";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_3" name="text_box_validation_3" action="#" method="post" onSubmit="javascript:return validate_login();">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">onsubmit event of the form</td>

</tr>

<tr>

<td align="right">User Name</td>

<td>

<input name="user_name" type="text" class="tb" id="user_name" maxlength="50" />

<label id="user_name_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Password</td>

<td>

<input name="password" type="password" class="tb" id="password" maxlength="50" />

<label id="password_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td></td>

<td>

<input name="btnLogin" type="submit" value="Login" id="btnLogin"/>

</td>

<td></td>

</tr>

<tr>

<td align="right">&nbsp;</td>

<td colspan="2">&nbsp;</td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>


</tr>

</tbody>

</table>

</form>

</body>

</html>



4. Validate integer values - onkeyup event of the textbox

In this example you can learn how to validate textbox in javascript at the vent of onkeyup. That means if you type incorrect value for the age field, it alerts you to enter a correct value for age. Also there is an example for validate textarea. There user have to enter at least 20 characters to the description field.

Syntax: <input name="age" type="text" class="tb" id="age" size="5" maxlength="50" onKeyUp="javascript:is_valid_integer(this);" />

Validate textbox and textare
Age 
Description
(Minimum 20 characters)
 
  
Copy and paste bellow code for validate textbox
and textarea.

<!DOCTYPE HTML>

<html>

<head>

<title>Validate Textbox</title>

<style type="text/css">

.ex_table{font-family:Verdana, Geneva, sans-serif;font-size:12px;}

.tb{border:1px solid #36F;}

.err_tb1{border:1px solid #F00;}

.err_tb2{background-color:#FFC4C4;}

.custom_error{background-image:url(http://3.bp.blogspot.com/-DSiKVnlbz8E/ULGxw6Gtz6I/AAAAAAAAB6I/UlgNBnJixws/s1600/error.png);background-repeat:no-repeat;background-position:right;}

.error_free{background-image:url(http://3.bp.blogspot.com/-1LRUjU_2OpA/ULGxvwfr-mI/AAAAAAAAB6A/DPoRn4y8iJI/s1600/accept.png);background-repeat:no-repeat;background-position:right;}

</style>

<script type="text/javascript">

var reg = /^[0-9]+$/;

function is_valid_integer(textField){

if(!reg.test(textField.value)){

alert("Please enter integers only");

textField.value="";

textField.focus();

return false;

}

}

function validate_form(){

var e = 0;

if(isEmpty("age", "Please enter Age", "age_info") || !reg.test(document.getElementById("age").value)){

e++

}

if(isEmpty("description", "Please enter Description", "description_info")){

e++

}else{

if(document.getElementById("description").value.length<20){

document.getElementById("description_info").innerHTML="Minimum 20 Characters";

e++

}

}

if(e > 0){

alert("Please fill form details correctly");

return false

}else{

return true

}

}

function isEmpty(e, t, n)

{

var r = document.getElementById(e);

var n = document.getElementById(n);

if(r.value.replace(/\s+$/, "") == "")

{

n.innerHTML = t;

r.value = "";

r.focus();

return true

}

else

{

n.innerHTML = "";

return false

}

}

</script>

</head>

<body>

<form id="text_box_validation_4" name="text_box_validation_4" action="#" method="post" onSubmit="javascript:return validate_form();">

<table border="0" class="ex_table">

<tbody>

<tr>

<td colspan="3" align="left">Validate textbox and textare</td>

</tr>

<tr>

<td align="right">Age</td>

<td>

<input name="age" type="text" class="tb" id="age" size="5" maxlength="50" onKeyUp="javascript:is_valid_integer(this);" />

<label id="age_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td align="right">Description<br/>(Minimum 20 characters)</td>

<td><textarea name="description" cols="30" rows="5" class="tb" id="description"></textarea><br/>

<label id="description_info" style="color: red; font-style: italic;"></label>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td></td>

<td>

<input name="btnSubmit" type="submit" value="Submit" id="btnSubmit"/>

</td>

<td></td>

</tr>

<tr>

<td align="right">&nbsp;</td>

<td colspan="2">&nbsp;</td>

</tr>

<tr>

<td colspan="3" align="right"><a href="http://kottawadumi.blogspot.com" target="_self">Programming Help</a></td>

</tr>

</tbody>

</table>

</form>

</body>

</html>