PHP class to validate Server side Data

PHP class to validate Server side Data

Client side Data validation is good but not as secure as Server side input data validation. If you only rely on client side data validation it may be possible your web application can be hacked or manipulated better use both client and server side validation of inputs. Client  side validation is done by JavaScript while Server side by PHP, Java, asp ….

In this tutorial I am going to create a file called validate.php , a class to validate user input.

First create a file called validate.php with code given below :

<?php
class Validate{
public function checkPresense($data){
if($data=="")
$response = true;
else
$response = false;
return $response;
}
public function checkString($data,$length){
if(strlen($data) < $length)
$response = true;
else
$response = false;
return $response;
}
public function checkInteger($data){
if(preg_match('/^\d+$/',$data)) {
$response = false;
} else {
$response = true;
}
return $response;
}
public function checkMobile($data,$length){
if(preg_match('/^\d{'.$length.'}$/',$data)  and $data[0]!=0){
$response = false;
}else{
$response = true;
}
return $response;
}
public function checkNumber($data,$length){
if(preg_match('/^\d{'.$length.'}$/',$data)){
$response = false;
}else{
$response = true;
}
return $response;
}
public function checkEmail($data){
if(!filter_var($data, FILTER_VALIDATE_EMAIL) === false){
$response = false;
}else{
$response = true;
}
return $response;
}
public function checkDate($data){
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$data))
{
$response = false;
}else{
$response = true;
}
return $response;
}
}
$validate =new Validate();
?>

Now we create a file demo.php

<?php
require 'validate.php';
//Validating empty field
$field1= "";
if($validate->checkPresense($field1)==true){
echo 'Field1 should not be empty';
}
//Validating string with less than
$field2= "xyz";
if($validate->checkString($field2,5)==true){
echo 'Field2 should not be less than 5 character';
}
//Validating string with less than
$email= "info@codentricks";
if($validate->checkEmail($email)==true){
echo 'Field2 should not be less than 5 character';
}
//Validating date in iso format 2017-05-15
$date = "15-04-2018"
if($sanjay->checkDate($date)){
echo "Check Date Formate";
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

Do you have any Query / Suggestion