This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Monday 17 September 2012

csv export and import script using php

Code bellow will be helpfull for you for importing and exporting csv files. Copy the code bellow and save it as "import_export_csv.php" then open it in your host e.g. 'localhost' and start importing, exporting csv files.

<?php
//don't forget to include your database connectivity.
 include('db_connection.php');
 if ($REQUEST_METHOD=="POST" && $_POST['btnSubmit']== 'Export') //this code is for exporting data when you click on "Export" this part of code will be executed.
 {
   // if you want to export data from a database table. You have to give your_table name in bellow query.
   $select = "SELECT * FROM Your_table";
   $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
// code bellow will get names of the fields and set as header of the csv.
   $fields = mysql_num_fields ( $export );
   for ( $i = 0; $i < $fields; $i++ )
   {
    $header .= '"'.mysql_field_name( $export , $i ).'"';
    if($i != $fields-1)
    $header .= ",";
   }
//if data found in database arrange it in csv format and pass to a variable $data.
   while( $row = mysql_fetch_row( $export ) )
   {
    $line = '';
    foreach( $row as $value )
    {                                           
     if ( ( !isset( $value ) ) || ( $value == "" ) )
     {
      $value = '"'."\t".'",';
     }
     else
     {
      $value = str_replace( '"' , '""' , $value );
      $value = '"' . $value . '"' . ",";
     }
     $line .= $value;
    }
 
    $line = substr($line, 0, -1);
    $data .= trim( $line ) . "\n";
   }
   $data = str_replace( "\r" , "" , $data );
//if data=='' not found in database
   if ( $data == "" )
   {
    $data = "\n(0) Records Found!\n";                       
   }
   header("Content-type: application/octet-stream");
   header("Content-Disposition: attachment; filename=products_csv.csv");
   header("Pragma: no-cache");
   header("Expires: 0");
// display fields name and data here
   print "$header\n$data";
   exit;
 }
 elseif ($REQUEST_METHOD=="POST" && $_POST['btnSubmit']== 'Import') //this code is for importing data when you click on "Import" this part of code will be executed.
 {
 
   if ($_FILES[csv][size] > 0)
   {
    //get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file, "r");
    $row=1;
 //fgetcsv — Gets line from file pointer and parse for CSV fields
    while (($line_of_data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
  //If your first line from csv contains fields names ignore it.
     if($row!=1)
     {
      // $line_of_data is numaric array has your impoted data $line_of_data[0] has your first record from csv which is fields name normaly.
      $query = "insert into yourtable (username, email) values ('$line_of_data[0]', '$line_of_data[1]')";
      mysql_query ($query) or die ( "Sql error : " . mysql_error( ) );
   
     }
      $row++;
        }
    echo "File imported successfuly.";
 
   }
 }
 ?>
 <div style="margin:0 auto; width:100%">
 <form method="post" name="form1" action="import_export_csv.php">
 click here for export a csv file: <input type="submit" name="btnSubmit" value="Export" />
 </form>
 </div>
 <div style="margin:10px auto; width:100%">
 <form method="post" name="form2" enctype="multipart/form-data" action="import_export_csv.php">
 select your .csv file: <input type="file" name="csv" />
 <input type="submit" name="btnSubmit" value="Import" />
 </form>
 </div>    

    

using google map lookup address by postal code

       

   <?php
    // First, we need to take their postcode and get the lat/lng pair:
    $postcode = 'SL1 2PH';
    // Sanitize their postcode:
    $search_code = urlencode($postcode);
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $search_code . '&sensor=false';
 //json_decode() returns an object pass 2nd parameter true to json_decode() if you want to get results as array
    $json = json_decode(file_get_contents($url), true);
 //print_r($json);  uncomment for seeing whole arry
     $lat = $json['results'][0]['geometry']['location']['lat'];
     $lng = $json['results'][0]['geometry']['location']['lng'];
    // Now build the lookup:
    $address_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&sensor=false';
 //json_decode() returns an object if you want to get results as array, pass 2nd parameter true e.g. json_decode(file_get_contents($address_url, true))
    $address_json = json_decode(file_get_contents($address_url), true);
    print_r($address_json['results'][0]['formatted_address']);
 ?>    

    

Monday 14 May 2012

How to write a php script for file downloading

In this tutorials you will learn how to write a php script for file downloading.If you want to see how to upload a file into a server click here.

<?php 
// Give the path here where your file is located and make a hyper link like <a href='www.yoursite.com?fname=youpic.jpg'>Download image</a>
//$_GET['fname']; will get the file name you given in hyper link and start downloading

$file = 'admin/upload/'.$_GET['fname'];
header("Expires: 0"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false); 
header("Pragma: no-cache"); 
header("Content-type: application/pdf");   
header('Content-length: '.filesize($file)); 
header('Content-disposition: attachment; filename='.basename($file)); 
readfile($file); 
// Exit script. So that no useless data is output-ed. 
exit; 
?> 

 

Wednesday 9 May 2012

Upload image into folder and save its name into database

This tutorial tell you how to Upload image into folder and save its name into database.
You should follow these two steps:
  1. Creat a database named 'olympic' and a table named 'acc_images'.
    CREATE TABLE IF NOT EXISTS `acc_images` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `acc_id` int(11) unsigned NOT NULL, `image` varchar(255) NOT NULL, `status` varchar(20) NOT NULL, PRIMARY KEY (`id`), );
  2. Copy and past code given below.
    <?php
    // Assigning value about your server to variables for database connection
    $hostname_connect= "localhost";
    $database_connect= "olympic";
    $username_connect= "root";
    $password_connect= "";
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    if($_POST)
    {
    // $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.

    if ($_FILES["file"]["error"] > 0)
    {
    // if there is error in file uploading
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    }
    else
    {
    // check if file already exit in "images" folder.
    if (file_exists("images/" . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {  //move_uploaded_file function will upload your image.  if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
    if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))
    {
    // If file has uploaded successfully, store its name in data base
    $query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
    if(mysql_query($query_image))
    {
    echo "Stored in: " . "images/" . $_FILES["file"]["name"];
    }
    else
    {
    echo 'File name not stored in database';
    }
    }
    }


    }
    }
    ?>
    <html>
    <body>
    <form action="" method="post"enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    </body>
    </html>

Tuesday 8 May 2012

Create a comma separated csv from sql query


<?php
$select = "SELECT * FROM Your_table";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
    $header .= '"'.mysql_field_name( $export , $i ).'"';
 if($i != $fields-1)
 $header .= ",";
}
while( $row = mysql_fetch_row( $export ) )
{

    if(isset($row[0]) && $row[0] != ''){
  $row[0] = text_decrypt($row[0]);
 }
 $line = '';
    foreach( $row as $value )
    {                                           
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . ",";
        }
        $line .= $value;
    }

 $line = substr($line, 0, -1);
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                       
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_file_name.csv");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>

Sunday 6 May 2012

Make a Sign in form and store data in session

This tutorial tell you how to match username and password entered by user with stored records in database. Then store username in session variable. You can see sing up form here
You should follow these two points:
  1. Creat a database named 'olympic' and a table named 'user'.
    CREATE TABLE IF NOT EXISTS `user` ( `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `postal_code` int(11) NOT NULL, `status` varchar(20) NOT NULL, `key` varchar(20) NOT NULL, `id` int(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
  2. Copy and past code given below.
    <?php
    // Assigning value about your server to variables for database connection
    $hostname_connect= "localhost";
    $database_connect= "olympic";
    $username_connect= "root";
    $password_connect= "";
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    if($_POST)
    {
    $username=$_POST['username'];
    $password=$_POST['password'];

    $user_query="select * from user where username='$username'and password='$password'";

    $user_result=mysql_query($user_query);
    $user_row=mysql_fetch_array($user_result);
    $id=$user_row['id'];
    $num_user=mysql_num_rows($user_result);
    // Above query matches username and password entered by user with database records.
    if($num_user==1)
    {
    // if username and password exist in database assign username to session.
    // echo $_SESSION['username'] where you want to display username to user in you website
    $_SESSION['username'] = $user_row['username'];
    $_SESSION['id']=$id;
    // redirect user to home page or where you want
    header('Location: index.php');
    }
    else
    {
    echo "Invalid User Name or Password";
    }
    }
    ?>


    <form id='register' action='' method='post'>
    <fieldset >
    <legend>Register</legend>
    <input type='hidden' name='submitted' id='submitted' value='1'/>
    <label for='username' >Username*: </label><br/>
    <input type='text' name='username' id='username' value="<?php if(!empty($username)) echo $username ?>" maxlength="50" /><br/>
    <label for='Password' >Password*:</label><br/>
    <input type='password' name='password' id='password' maxlength="50" /><br/>
    <input type='submit' name='Submit' value='Submit' />
    </fieldset>
    </form>

How to save form data in database and send activation key

In this tutorial you will learn how to save signup form data in database and send activation key to user's email. I am not including validation code here if you want to validate your form submission code click here to see. For looking the sign in form click here
You should follow these two points:
  1. Creat a database named 'olympic' and a table named 'user'.
    CREATE TABLE IF NOT EXISTS `user` ( `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `postal_code` int(11) NOT NULL, `status` varchar(20) NOT NULL, `key` varchar(20) NOT NULL, `id` int(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
  2. Copy and past code given below.
    <?php
    // Assing value about your server to these variables for database connection
    $hostname_connect= "localhost";
    $database_connect= "olympic";
    $username_connect= "root";
    $password_connect= "";
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    if($_POST)
    {
    $key = mt_rand(); // this mt_rand() function genrates randum key for you
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $passconf = $_POST['passconf'];
    $postal_code = $_POST['postal_code'];

    // code below checks username in database exist or not. if exist data will not submit to database
    $user_query="select username from user where username='$username'";

    $user_result=mysql_query($user_query);
    $user_row=mysql_fetch_array($user_result);
    if(!empty($user_row))
    {
    if($user_row['username'])
    {
    echo 'Username Already exist';
    }


    }
    else
    {
    //If username not already exist then insert data into 'user' table
    $q = "INSERT INTO `user`(`username`,`email`,`password`,`postal_code`,`key`,`status`)VALUES('$username','$email','$password','$postal_code','$key','InActive')";

    $qr=mysql_query($q);
    if(!$qr){
    echo "Not Submitted";
    }
    else
    {
    // if data has saved in data base then code below will send email to user
    $to = $email;
    $subject = "Activation key";
    $message = "Your activation key is this" .$key.'<br>'.' click here to activate your acount.<a href="localhost">here</a>';
    $from = "admin_abc@yahoo.com";
    $headers = "From:" . $from;
    if(mail($to,$subject,$message,$headers))
    {
    echo "Check your email to activate your acount.";
    }
    else
    {
    echo "Email not sended";
    // if you are working on localhost email will not send and below line helps you to activates your acount
    echo $message = "Your activation key is this " .$key.'<br>'.' click here to activate your acount. <a href="activation.php?key='.$key.'">here</a>';
    }
    }
    }
    }
    ?>
    <html>
    <body>
    <form id='registeration' action='' method='post' >
    <fieldset >
    <legend>Register</legend>
    <input type='hidden' name='submitted' id='submitted' value='1'/>
    <label for='username' >Username*: </label><br/>
    <input type='text' name='username' id='username' value="<?php if(!empty($username)) echo $username ?>" maxlength="50" /><br/>
    <label for='email' >Email Address*:</label><br/>
    <input type='text' name='email' id='email' value="<?php if(!empty($email)) echo $email ?>" maxlength="50" /><br/>
    <label for='password' >Password*:</label><br/>
    <input type='password' name='password' id='password' maxlength="50" /><br/>
    <label for='passconf' >Confirm Password*:</label><br/>
    <input type='password' name='passconf' id='password' maxlength="50" /><br/>
    <label for='postal_code' >Postal Code*:</label><br/>
    <input type='text' name='postal_code' id='postal_code' value="<?php if(!empty($postal_code)) echo $postal_code ?>" maxlength="50" /><br/>
    <input type='submit' name='Submit' value='Submit' />
    </fieldset>
    </form>
    </body>
    </html>

Sunday 15 April 2012

PHP Validation for complete SignUp form

For PHP validation I am using the same regular expression rules as I have used and described in detail during java script validation for complete signup form. Below is complete PHP validation code. Copy and paste it in your text editor and save it with PHP extension (e.g. validation.php). Then open it in localhost server you will see it working well.
Code bellow has two parts:
  1. HTML which contains html form which you can see on your browser
  2. PHP which get user data using the globle variable $_POST and validates it using the regular expression
<?php
if($_POST['submit'] == 'Submit')
{
//If user click on submit button we get value by using $_POST where names in sequre brackets are the names of form's input fields.
$username = $_POST['username'];
$email = $_POST['email'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$passconf = $_POST['passconf'];

// Now you check if $username is empty you assign coresponding error message to an associative array named $error. You can display error message for your user using this array in HTML part.
if($username=='')
{
$error['username']= 'Please enter username <br>';
}

else if(!ereg("^[a-zA-Z0-9_]{3,16}$", $username))
{
// else codition checks if username not contains alpha-numeric characters and it is less than 3 characters or more than 16 characters. It assign error message to $error array. Validate similaely other data email, phone etc.
$error['username']= 'please enter valid username<br>';

}

if($email=='')
{
$error['email']= 'Please enter email <br>';
}
else if(!ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $email))
{
$error['email']= 'please enter valid email<br>';
}

if($password=='')
{
$error['password']= 'Please enter password<br>';
}
else if(strlen($password)<6)
{
$error['password']= 'Password is too short.<br>';
}
if($passconf=='')
{
$error['passconf']= 'Please confirm password<br>';
}
else if($password!=$passconf)
{
$error['passconf']= 'password does not match<br>';
}

if($firstname=='')
{
$error['firstname']= 'Please enter firstname<br>';
}
else if(!ereg("^[a-zA-Z]{3,16}$", $firstname))
{
$error['firstname']= 'please enter valid firstname<br>';
}
if($lastname=='')
{
$error['lastname']= 'Please enter lastname<br>';
}
else if(!ereg("^[a-zA-Z]{3,16}$", $lastname))
{
$error['lastname']= 'please enter valid lastname<br>';
}
if($phone=='')
{
$error['phone']= 'Please enter phone<br>';
}
else if(!ereg("^[0-9]{3,16}$", $phone))
{
$error['phone']= 'please enter valid phone<br>';
}
 //if error not exist store data into database or send to email server.
 if(count($error)==0)
 {
  // You can see following links for storing data into database.
  // http://b2atutorials.blogspot.com/2012/05/how-to-save-sign-up-form-data-in.html
  // http://b2atutorials.blogspot.com/2013/06/how-to-store-data-into-database-easily.html
 }
}
?>
<html>
<body>
<form name="signup" action="" method="post">
<ul>
<li>
<p>Username:</p>
<p><?php
//Now check if $error['username'] is not empty display the error message you have assign it above.
if(!empty($error['username'])) echo $error['username']; ?></p>
<p><input type="text" name="username" value="<?php if(!empty($username)) echo $username ?>" size="50" /></p>
</li>
<li>
<p>Email:</p>
<p><?php if(!empty($error['email'])) echo $error['email']; ?></p>
<p><input type="text" name="email" value="<?php if(!empty($email)) echo $email ?>" size="50" /></p></li>
<li><p>Password:</p>
<p><?php if(!empty($error['password'])) echo $error['password']; ?></p>
<p><input type="password" name="password" value="<?php if(!empty($password)) echo $password ?>" size="50" /></p></li>
<li>
<p>Password Confirm:</p>
<p><?php if(!empty($error['passconf'])) echo $error['passconf']; ?></p>
<p><input type="password" name="passconf" value="<?php if(!empty($passconf)) echo $passconf ?>" size="50" /></p></li>
<li>
<p>First Name:</p>
<p><?php if(!empty($error['firstname'])) echo $error['firstname']; ?></p>
<p><input type="text" name="firstname" value="<?php if(!empty($firstname)) echo $firstname ?>" size="50" /></p></li>
<li>
<p>Last Name:</p>
<p><?php if(!empty($error['lastname'])) echo $error['lastname']; ?></p>
<p><input type="text" name="lastname" value="<?php if(!empty($lastname)) echo $lastname ?>" size="50" /></p></li>
<li>
<p>Phone:</p>
<p><?php if(!empty($error['phone'])) echo $error['phone']; ?></p>
<p><input type="text" name="phone" value="<?php if(!empty($phone)) echo $phone ?>" size="50" /></p></li>
<li>
<p><input type="submit" name="submit" value="Submit" /></p>
</li></ul>
</form>
</body>
</html>

 

Wednesday 28 March 2012

how to update value using join between two tables in mysql

This example may be help full for you.

UPDATE xcart_products INNER JOIN xcart_extra_field_values
ON xcart_extra_field_values.productid = xcart_products.productid
SET xcart_products.forsale = 'N'
WHERE xcart_extra_field_values.value = 'article' and xcart_extra_field_values.fieldid=1

Thursday 1 March 2012

Complete code with html sign up form and validation:



Copy and past given code in notepad and save it with .html for demo. Click here for detail 

<head>
<script type="text/javascript">
function validation_for_signup()
{

                var check_email = /^[\w\.]+@[a-zA-Z_]+?\.[a-zA-Z\.]{2,6}$/;
                var check_username = /^[a-zA-Z0-9_]{3,16}$/;
                var check_name = /^[a-zA-Z]{3,16}$/;
                var check_phone = /^[0-9]{3,16}$/;
                                if(document.signup.username.value=="")
                                {
                                                alert("please enter username");
                                                document.signup.username.focus();
                                                return false;
                                }
                                else if(check_username.test(document.signup.username.value) == false)
                                {
                                                alert('Invalid  username');
                                                document.signup.username.focus();
                                                return false;
                                }
                                if(document.signup.email.value=="")
                                {
                                                alert("please enter email");
                                                document.signup.email.focus();
                                                return false;
                                }
                                else if(check_email.test(document.signup.email.value) == false)
                                {
                                                alert('Invalid  email');
                                                document.signup.email.focus();
                                                return false;
                                }
                                if(document.signup.password.value=='')
                                {
                                                alert("Please enter Password.");
                                                document.signup.password.focus();
                                                return false;
                                }
                                else if(document.signup.password.value.length<6)
                                {
                                                alert("Password is too short.");
                                                document.signup.password.focus();
                                                return false;
                                }
                                if(document.signup.passconf.value=='')
                                {
                                                alert("Please confirm Password.");
                                                document.signup.passconf.focus();
                                                return false;
                                }
                                else if(document.signup.password.value!=document.signup.passconf.value)
                                {
                                                alert("Password does not match.");
                                                document.signup.password.focus();
                                                return false;
                                }
                               
                                if(document.signup.firstname.value=="")
                                {
                                                alert("please enter firstname");
                                                document.signup.firstname.focus();
                                                return false;
                                }
                                else if(check_name.test(document.signup.firstname.value) == false)
                                {
                                                alert('Invalid  firstname');
                                                document.signup.firstname.focus();
                                                return false;
                                }
                                if(document.signup.lastname.value=="")
                                {
                                                alert("please enter lastname");
                                                document.signup.lastname.focus();
                                                return false;
                                }
                                else if(check_name.test(document.signup.lastname.value) == false)
                                {
                                                alert('Invalid  lastname');
                                                document.signup.lastname.focus();
                                                return false;
                                }
                                if(document.signup.phone.value=="")
                                {
                                                alert("please enter phone");
                                                document.signup.phone.focus();
                                                return false;
                                }
                                else if(check_phone.test(document.signup.phone.value) == false)
                                {
                                                alert('Invalid  phone');
                                                document.signup.phone.focus();
                                                return false;
                                }
}


</script>
</head>

<body>

<form name="signup" action="" onSubmit="return validation_for_signup()" method="post">

<ul>

<li>
<p>Username:</p>
<p><input type="text" name="username" value="" size="50" /></p></li>

<li>
<p>Email:</p>
<p><input type="text" name="email"  value="" size="50" /></p></li>

<li><p>Password:</p>
<p><input type="password" name="password"  value="" size="50" /></p></li>
<li>
<p>Password Confirm:</p>
<p><input type="password" name="passconf"  value="" size="50" /></p></li>
<li>
<p>First Name:</p>
<p><input type="text" name="firstname"  value="" size="50" /></p></li>
<li>
<p>Last Name:</p>
<p><input type="text" name="lastname"  value="" size="50" /></p></li>
<li>
<p>Phone:</p>
<p><input type="text" name="phone"  value="" size="50" /></p></li>
<li>
<p><input type="submit" value="Submit" /></p>
</li></ul>
</form>

</body>

Javascript Validation for complete SignUp form


Using client side JavaScript validation is an efficient way to validate the user input in web forms.
Form validation is the process of checking that a form has been filled in correctly before it is processed.
There are two main methods for validating forms: server-side (using ASP, PHP, etc), and client-side (usually done using JavaScript). Server-side validation is more secure but often more tricky to code, whereas client-side (JavaScript) validation is easier to do and quicker too.
In this tutorial I have built a complete sign up form with client-side JavaScript validation. Here is complete code
Below is form starting tage in which onSubmit event I call a validation function named validation_for_signup().
<form name="signup" action="" onSubmit="return validation_for_signup()" method="post">
Validation for Username field:

function validation_for_signup()
{
                var check_username = /^[a-zA-Z0-9_]{3,16}$/;
                                if(document.signup.username.value=="")
                                {
                                                alert("please enter username");
                                                document.signup.username.focus();
                                                return false;
                                }
                                else if(check_username.test(document.signup.username.value) == false)
                                {
                                                alert('Invalid  username');
                                                document.signup.username.focus();
                                                return false;
                                }
}

This function uses a variable check_name to which a regular expression rule is assigned. This regular expression only allows alpha-numeric digits and underscore when we will compare it with user’s entered value.
We uses document.signup.username.value for getting value from username field.
Where  document is the parent object of  "form",  signup’ is the name of  the form, username is the  name of  the text field and value  is the value of  input field named username.
If condition cheches either value is empty or not. If  user not filled the box  pop ups a message “please enter username”. For this purpose we uses alert(‘please enter username’). This is a built in fucntion of java script.
Document.signup.username.focus()
This built in function focus the username field when user chlick ok from pop up.
Return false;
This stops the form submition. If  you return true the form will be submitted either value is empty or not.
Else If condition cheches either test(document.signup.username.value) function returns true or false. If false a message will pop up “invalid username”.  test() function matches either value is following the rule defined in regular expression or not for this purpose i uses check_username.test(document.signup.username.value). It  returns true if user entered value is according to rule defined and assigned to variable check_username else it returns false.

Validation for Email field:

If you have read validation for username field it will be same only we have to define regular expression rule different from rule we defined for username field. For example.

function validation_for_signup()
{
                var check_email = /^[\w\.]+@[a-zA-Z_]+?\.[a-zA-Z\.]{2,6}$/;
                                if(document.signup.email.value=="")
                                {
                                                alert("please enter email");
                                                document.signup.email.focus();
                                                return false;
                                }
                                else if(check_email.test(document.signup.email.value) == false)
                                {
                                                alert('Invalid  email');
                                                document.signup.email.focus();
                                                return false;
                                }
}
Validation for Password field:


function validation_for_signup()
{
                if(document.signup.password.value=='')
                                {
                                                alert("Please enter Password.");
                                                document.signup.password.focus();
                                                return false;
                                }
                                else if(document.signup.password.value.length<6)
                                {
                                                alert("Password is too short.");
                                                document.signup.password.focus();
                                                return false;
                                }
                                if(document.signup.passconf.value=='')
                                {
                                                alert("Please confirm Password.");
                                                document.signup.passconf.focus();
                                                return false;
                                }
                                else if(document.signup.password.value!=document.signup.passconf.value)
                                {
                                                alert("Password does not match.");
                                                document.signup.password.focus();
                                                return false;
                                }
}
Validation for Firstname, Lastname and for Phone Number:

It is very simple only you have to define regular expression rules for firstname and lastname which allow only alphabetic and for phone number which allow only numeric. The rules I have defined below also matches that minimum length of entered value must be 3 and maximum  length must be 16, You may change it according your requirement.

 function validation_for_signup()
{
                var check_name = /^[a-zA-Z]{3,16}$/;
                var check_phone = /^[0-9]{3,16}$/;
                                if(document.signup.firstname.value=="")
                                {
                                                alert("please enter firstname");
                                                document.signup.firstname.focus();
                                                return false;
                                }
                                else if(check_name.test(document.signup.firstname.value) == false)
                                {
                                                alert('Invalid  firstname');
                                                document.signup.firstname.focus();
                                                return false;
                                }
                                if(document.signup.lastname.value=="")
                                {
                                                alert("please enter lastname");
                                                document.signup.lastname.focus();
                                                return false;
                                }
                                else if(check_name.test(document.signup.lastname.value) == false)
                                {
                                                alert('Invalid  lastname');
                                                document.signup.lastname.focus();
                                                return false;
                                }
                                if(document.signup.phone.value=="")
                                {
                                                alert("please enter phone");
                                                document.signup.phone.focus();
                                                return false;
                                }
                                else if(check_phone.test(document.signup.phone.value) == false)
                                {
                                                alert('Invalid  phone');
                                                document.signup.phone.focus();
                                                return false;
                                }
}
Click here for complete html form and validation