PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

PHP Forms Advanced Validation

In this chapter, we will validate name, email, password, website, description, gender, remember me inputs.

Input FieldValidation
NameRequired. Should only contain letters, numbers and white spaces.
EmailRequired. Should be a valid email.
PasswordRequired. Should be longer than 6 characters.
WebsiteOptional. If set, should be a valid URL.
DescriptionOptional. Multi-line text area input.
GenderRequired. Radio Button Input.
Remember MeTrue of False. Default is false. Check box input.

Primary Validating Function

In the previous examples, we validated string using both trim() and htmlspecialchars() function like. trim(htmlspecialchars($string)). But, it is a really bad practice for a good developer as it can make errors. To prevent this code repetition error, let's create our own function to do both in one function call.

We will name it validate(). This function will remove white spaces and escape html to prevent xss at the same time.

Validate Function


<?php
function validate($str) {
	return trim(htmlspecialchars($str));
}

// calling validate function
echo '<pre>';
echo validate('  <script>  ');
echo '</pre>';

Run Example ››

Complete HTML Form

Here we will create a complete HTML form which has all kinds of input fields.

HTML Form


<html>
<head>
	<title></title>
</head>
<body>
<form method="POST" action="">
	Name: <input type="text" name="name"> <br>
	Email: <input type="text" name="email"> <br>
	Password: <input type="password" name="password"> <br>
	Website: <input type="text" name="website"> <br>
	Description: <textarea name="description"></textarea> <br>
	Gender: Male<input type="radio" name="gender" value="male"> Female<input type="radio" name="gender" value="female"> <br>
	Remember Me: <input type="checkbox" name="remember">
</form>
</body>
</html>

Run Example ››

Name Validation

This code will check whether the name only contains letters, numbers and white spaces. If it contains invalid characters, the error message will be stored in $nameError variable to show later in our form.


$name = validate($_POST['name']);
if (!preg_match('/^[a-zA-Z0-9\s]+$/', $name)) {
	$nameError = 'Name can only contain letters, numbers and white spaces';
}

Email Validation

We use in-built function filter_var() with FILTER_VALIDATE_EMAIL flag to validate emails. The filter_var() can be used for many purposes. To say that we are using it to validate an email, we have to set the second parameter (called as flag) to FILTER_VALIDATE_EMAIL.


$email = validate($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
	$emailError = 'Invalid Email';
}

Password Validation

We made a rule that password should be longer than 6 characters. We will validate it here.


$password = validate($_POST['password']);
if (strlen($password) < 6) {
	$passwordError = 'Please enter a long password';
}

URL (Website) Validation

Here we use filter_var() function with FILTER_VALIDATE_URL flag.s


$website = validate($_POST['website']);
if (!filter_var($website, FILTER_VALIDATE_URL)) {
	$websiteError = 'Invalid URL';
}

The only validation should be done to description input is, sending the input though the validate() function we created earlier.

Then, we need to check whether the gender is set.

Check Box (Remember Me) Validation

Most of browsers set value of check box to "on" if it is checked. We use filter_var() function with FILTER_VALIDATE_BOOLEAN flag to convert it to boolean. This function will convert "on" to true, which makes later processes easy for us.


$remember = validate($_POST['remember']);
$remember = filter_var($remember, FILTER_VALIDATE_BOOLEAN);
// now $remember is a boolean

Did you know? There's a #Group for you to get help on PHP.
Profile Picture
Supun Kavinda
I'm the Founder of Hyvor, Web Developer, Physics Lover, Flutist, and a Table Tennis Player.
My Websites