articles

Home / DeveloperSection / Articles / Validations in PHP

Validations in PHP

Royce Roy 3991 03-Jun-2016

Validation is used to check whether user has submitted the input or not. There are two types of validation:

·    Client side validation: Validation is performed on the client machine web browser.

·    Server Side validation: After submitted by user,The data has sent to a server and perform validation checks in server machine.

Client Side validation:

Client side validation is done by using Javascript. Javascript validation is one of the common features used by language. Interactive websites contains dynamic content that requires user input and that input must be valid.

Code Implementation:

Step1: First we will create an HTML Form . Let the name of the page form.php:

<center>

<div class="user">
<!-- Creating a form: -->
<form method="post" name="myForm" onsubmit="return validate()">
<h2><u>REGISTRATION FORM</u></h2>
<table>
<tr><td>Username:</td><td colspan="3"><input type="text" name="uname" class="user1"></td></br>
<tr><td>Password:</td><td colspan="3"><input type="password" name="pass" class="user1"></td></br>
<tr><td>Name :</td><td colspan="3"><input type="text" name="name" class="user1"></td></br>
<tr><td>D.O.B:</td><td><select name="year" class="date" id='year'>
<option value='Select' selected="selected">Year</option>
<?php
for($i=date('Y');$i>=1980;$i--){
 echo("<option>$i</option>");
   }
?>
</select></td>
<td><select name="month" class="date" id='month'>
<option value='Select' selected="selected">Month</option>
<?php
$array=array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'April',5=>'May',6=>'June',7=>'Jul',8
=>'Aug',9=>'Sep',10=>'Oct',11=>'Nov',12=>'Dec');
     foreach($array as $k=>$v){
 echo("<option value='$k'>$v</option>");
    }  
?>
</select></td>
<td><select name="day" id='day' class="date">
<option value='Select' selected="selected">Day</option>
<?php
for($i=1;$i<=31;$i++){
 echo("<option>$i</option>");
 }  
?>
</select></br></td></tr>
<tr><td>Phone:</td><td colspan="3"><input type="number" name="phone" class="user1"></br></td></tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" name="submit" value="Submit" class="user3"></br></td></tr>
</table>
</form>
</div>
<?php
require_once(“script_validation.php”);
?>


Step 2: Create script_validation.php:  


<?php
//connection is made with database
$con = mysqli_connect("localhost","username",”password”, 'database name');
//when the form is submmited it will insert the values entered by user
if(isset($_POST["submit"]))
{  
            $uname=$_POST["uname"];
            $pass=$_POST["pass"];
            $name=$_POST["name"];
            $dob=$_POST["year"]."-".$_POST["month"]."-".$_POST["day"];
            $phone=$_POST["phone"];

//It will insert the value in database which is enterd by the user.
$con->query("insert into user_login values('$uname','$pass','$name','$dob',$phone)");
 }
?>
//client side validation
<script>
function validate()
{
//If any of the fields is left empty or null,this function will validate the fields and alerts a message to returns false,to prevent the form being submitted
              var uname=document.forms["myForm"]["uname"].value;
           var uname=document.forms["myForm"]["pass"].value;
           var uname=document.forms["myForm"]["name"].value;
           var uname=document.forms["myForm"]["phone"].value;  

   if(uname == null || uname == "" )
             {
                         alert("Username must be filled.");
                         return false;
            }
   if (document.getElementById('year').value == 'Select')
           {
                        alert("Please select Year");
                     return false;
           }
  else if (document.getElementById('month').value == 'Select')
          {
                       alert("Please select Month");
                       return false;
          }
   else if (document.getElementById('day').value == 'Select')
         {
                       alert("Please select Day");
                       return false;

         }



</script>

Code Output:

Now, lets run our sample, and check whether it validate form data or not. Left all the fields blank with null values and try to submit, the form will immediately popup a message “UserName must be filled”.

Similarly, left the other fields blank and check whether it validate form and show appropriate message or not.

 Validations in PHP

Server Side validation:

In this post you’ll learn Server side validation using PHP. Validation using PHP are considered to be more secure .PHP has a wide variety of functions and features which is used to validate a form.

<?php

//when the form is submmited it will insert the values entered by user
if(isset($_POST["submit"]))
{
       $uname=$_POST["uname"];
       $pass=$_POST["pass"];
       $name=$_POST["name"];
       $day = $_POST["day"];
       $month = $_POST['month'];
       $year = $_POST["year"];
       $dob= $year."-".$month."-".$day;
       $phone=$_POST["phone"];
//connection is made with database
$con = mysqli_connect("localhost","username",”password”, 'database name');
//It will insert the value in database which is enterd by the user 
       $con->query("insert into user_login values('$uname','$pass','$name','$dob',$phone)");
           if(empty($uname))//if username is empty than message would be given                  {                       $msg= "Please enter Username";                 } 

             else                 { 
                       if(empty($pass)) //if password is empty than message would be given
                {
                 $msg= "Please enter Password";
                 } 
                 else if(empty($name)) //if name is empty than message would be given                  { 
                $msg= "Please enter Name";
                 }
               else if(empty($year)) //if Year is empty than message would be given                  { 
                $msg= "Please enter Year"; 

                 }
         else if(empty($month)) //if month is empty than message would be given
                {
                   $msg= "Please enter Month";
                 }
        else if(empty($day)) //if Day is empty than message would be given
                 {
                   $msg= "Please enter Day";
                 }
        else if(empty($phone)) //if phone is empty than message would be given
                 {
             ?>
           <strong style=background-color:red>Please enter Phone</strong>
           <?php
                 }
       }
}
?>
//Style is used in the form
<style>
input[type=text],input[type=number],input[type=password]
 {
    padding: 10px 20px;
    margin: 3px 0;
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 6px;
    box-sizing: border-box;
          marg
}
.user
{
   background-color:lightgrey;
   width:40%;
   margin-top:20px;
   }
</style>

 Code Output:

Now, lets run our sample, and check whether it validate form data or not. Left all the fields blank with null values and try to submit, the form will immediately popup a message “Please enter username”.

Similarly left the other fields blank and check whether it validate form and show appropriate message or not. 

Validations in PHP

Validation using Regular Expression (Server side):

We will show you how to validate names, e-mails and URL’s:

 PHP-Validate e-mails:

The code below show the validation in e-mail :

Step1: Create an HTML page email.php

<style>
.text {
     text-align:center;
           line-height:525px;
</style>
<form method="post" class="text">
<input type="text" name="email">
<input type="submit" name="sub">
</form>
<?php
requie_once(“validate.php”);
?>

 Step2: Create validate.php:

<?php
//when the form is submmited it will insert the values entered by user
if(isset($_POST["sub"]))
{
$email=$_POST["email"];
//the pattern is "any letter or number followed by @ followed by any letter or number
//followed by . followed by 2-4 letters and maybe another.
$okay = preg_match(
        '/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/', $email
);
if ($okay) {
    echo $email." is valid<br />";
} else {
    echo $email." is invalid<br />";
}
}
?>
</form>
 
Code Output:

Here is the output of e-mail validation:

Validations in PHP

PHP-Validate name:

The code below show the validation in name:

Step1: Create  an HTML page name.php

     <form method="post">

               Name: <input type="text" name="name">
      <span class="error"></span>
      <input type="submit" name="sub">
      </form>
<?php
 require_once(“validate.php”);
?>

 Step2: Create validate.php: 

<?php

  if(isset($_POST["sub"]))
{
  $name = $_POST["name"];
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      echo "Only letters and white space allowed";
    }
}

  ?>
 
Code Output:

When you will enter numbers, symbols or other than letters it will show a message “Only letters and white spaces are allowed”.

Validations in PHP

PHP-Validate number:

The code below show the validation in number:

Step1: Create  an HTML page number.php

  <form method="post">

    <input type="text" name="number">
    <input type="submit" name="submit">
</form>
<?php
require_once(“validate.php”);
?>

 Step2: Create validate.php

<?php

if(isset($_POST["submit"]))
{
    $num = $_POST['number'];
    if (!preg_match('/^[0-9]*$/', $num))
    {
        echo("Only number should be entered");
    } else
    {
       echo("Valid");
    }
}
?>

Code Output:

When you will enter letters, symbols or other than number it will show a message “Only number should be entered”.

 Validations in PHP

PHP-Validate Password:

The code below show the validation in password:

Step1: Create  an HTML page password.php

 

<form method="post">

   <input type="text" name="password">
   <input type="submit" value="submit" name="submit">
</form>
<?php
require_once(“validate.php”);
?>

Step2: Create validate.php

<?php
if(isset($_POST["submit"]))
{
if(!empty($_POST["password"]) )
{
        $password = $_POST["password"];
        if (strlen($_POST["password"]) <= '8') {
            echo "Your Password Must Contain At Least 8 Characters!";
        }
        elseif(!preg_match("#[0-9]+#",$password)) {
            echo "Your Password Must Contain At Least 1 Number!";
        }
        elseif(!preg_match("#[A-Z]+#",$password)) {
             echo "Your Password Must Contain At Least 1 Capital Letter!";
        }
        elseif(!preg_match("#[a-z]+#",$password)) {
             echo "Your Password Must Contain At Least 1 Lowercase Letter!";
        }
    }
          }
          ?>

 

Code Output:

Your password must contain minimum 8 characters which include 1 uppercase letter, 1 lowercase and 1 number.

Validations in PHP


Updated 07-Sep-2019

Leave Comment

Comments

Liked By