Validation of input data using PHP

We must need to validate data before manipulating and performing operation on it. Most of websites contains client side validation however server side validation is important because client side validation may fail due to older verson of browser or disabled JavaScript. I am writing this post, in which include various tricks for validating different types of data.

Check Variable exist or not
Before check for valid values we must need to check for whether those variables are exist or not. This is important in case of $_GET and $_POST. for this isset() is used.

<?php
	if (! isset($_GET['name']))
	{
		echo "Missing name!";
	}
?>

Check for null
We also must need to check whether variable contains any value or not.For this we can use empty() of php. Normally most of developers are combine isset() and empty() in single if statement.

<?php
	if (!isset($_GET['name']) || empty($_GET['name]))
	{
		echo "Enter name!";
	}
?>

Validating Date
For date validation we can use checkdate() function in php which is predefined. This function take 3 arguments i.e. month, day, year. It will return true for valid date.

<?php
	$mm = 2; $dd = 29; $yy = 2012';
	if (! checkdate($mm, $dd, $yy))
	{
		echo "Enter valid date.";
	}
?>

Validating Mail Address
We can validate email id in 2 ways. The first is use filter_var() is predefined function in php and second is using regular expressions. However filter_var() is suggested over regex.

<?php
	$email = 'wrong_mail_id';
	if (! filter_var($email, FILTER_VALIDATE_EMAIL))
	{
		echo "Enter valid mail id.";
	}
?>

Validating IP Address
We can even also validate IP address in php. Same as mail validation we can also use filter_var() for IP address.

<?php
	$ip = '192.168.1.255';
	if (! filter_var($ip, FILTER_VALIDATE_IP))
	{
		echo "Enter valid IP address.";
	}
?>

One thought on “Validation of input data using PHP

Leave a Reply

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