Regular Expressions in PHP for From Validation

Sunday, August 14, 2011

As you working in any project regular expressions are very usefull to Form Validation,
here is some of Regular expression which is frequently used for form validation:

  • Email Validation
  • Mobile/Phone Number validation
  • Strong Password validation
  • IP Address Validation
  • Uploaded Image File Validation

<?php

// Valid Email Address Number or Not

	$email="master@example.com";
	if(preg_match('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$email))
	{
		echo "<br>Valid Email Address";
	}else
	{
		echo "<br>Invalid ";
	}
	
// Valid Phone Number or Not

	$phone="434-333-4454";
	if(preg_match('/[(]?\d{3}[)]?\s?-?\s?\d{3}\s?-?\s?\d{4}/',$phone))
	{
		echo "<br>Valid Phone Number";
	}else
	{
		echo "<br>Invalid Phone Number";
	}
	

// Valid Strong Password or Not (Check password with Digits Caps Small Letters symols )

	$password="A4z#s3";
	if(preg_match('/(?!^[0-9]*$)(?!^[a-zA-Z!@#$%^&amp;*()_+=<&gt;?]*$)^([a-zA-Z!@#$%^&amp;*()_+=<&gt;?0-9]{6,15})$/',$password))
	{
		echo "<br>Strong Password";
	}else
	{
		echo "<br>Weak Password";
	}
	

// Valid IPv4 Address or Not 0.0.0.0 to 255.255.255.255

	$ipaddress="128.222.234.182";
	if(preg_match('/\b[12]{1}(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\.[12]?(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\.[12]?(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\.[12]{1}(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\b/',$ipaddress))
	{
		echo "<br>Valid IP Address";
	}else
	{
		echo "<br>Invalid IP Address";
	}

// Valid Image or Not (jpg|gif|png)

	$imagefile="mypicture.jpg";
	if(preg_match("/^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$/",$imagefile))
	{
		echo "<br>Valid Image file";
	}else
	{
		echo "<br>Invalid Image file";
	}
	
?>


No comments:

Post a Comment