Get Website Learn Coding Tech Story

PHP Programming Examples

<!DOCTYPE html>
<html>
	<head>
		<title>Form Validation</title>
	</head>
	<body>
		<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
			<input type="text" name="name" placeholder="Name" /><br />
			<input type="email" name="email" placeholder="E-mail" /><br />
			<input type="tel" name="ph" placeholder="Phone Number" /><br />
			<input type="url" name="website" placeholder="Website" /><br />
			<input type="submit" name="submit" value="Submit" />
		</form>
		<?php
			if(isset($_POST['submit'])) {
			
				/* Checking length of the string */
				if(strlen($_POST['name']) > 3) {

					/* Matching name with regular expression */
					if(!preg_match("/^[a-zA-Z ]*$/",$_POST['name']))
						echo "<br />Only letters and white space allowed";
				} 
				else
					echo "<br />Invalid name!";
				
				if(strlen($_POST['email']) != 0) {

					/* Validate email using 'filter_var()' */
					if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) 
						echo "<br />Invalid email format!";
				}
				else
					echo "<br />E-mail can't be empty!";

				if(strlen($_POST['ph']) != 0) {

					/* 'ctype_digit()' checking numeric characters */
					if(strlen($_POST['ph']) < 10 || !ctype_digit($_POST['ph'])) 
						echo "<br />Invalid phone number!";
				}
				else
					echo "<br />Phone number can't be empty!";
				
				if(strlen($_POST['website']) != 0) {

					/* Matching URL with regular expression */
					if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $_POST['website'])) 
						echo "<br />Invalid web URL!";
				}
				else
					echo "<br />Web URL can't be empty!";
			}
		?>
	</body>
</html>


          /****** Output ******/
          

Input:

Name = Geek24

E-mail = contact@gmail

Phone = 984521

Website = www.geekboots.com


Only letters and white space allowed

Invalid email format!

Invalid phone number!!

Invalid web URL!

Learn more about strlen, preg_match, filter_var and ctype_digit