DONATE Hyvor Developer
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

PHP Forms Advanced Validation

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

Input Field Validation
Name Required. Should only contain letters, numbers and white spaces.
Email Required. Should be a valid email.
Password Required. Should be longer than 6 characters.
Website Optional. If set, should be a valid URL.
Description Optional. Multi-line text area input.
Gender Required. Radio Button Input.
Remember Me True 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

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.


<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">

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