An In-Depth Explanation of PHP Form Validation

Form Validation is a necessary process before the data entered in the form is submitted to the database. This is done to avoid unnecessary errors. In PHP Form validation, the script checks for data in respective fields based on the rules set by the developer, and returns an error if it does not meet the requirements.

Types of Validation

Depicted below is the table on the different types of fields present in the registration form, their requirements, and the field type, i.e., Required or Optional.

Field

Requirement

Field Type

Full Name

Only letters and spaces

Required

Email

Valid email address with “@”

Required

Website

Valid Web Address with “.com”

Optional

Gender

Must select one

Required

Comment

No requirements

Optional

In the above table, every field marked required is a compulsory field. Hence, without filling the field, you cannot submit the form. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

The table shows the field’s name; the requirement set for the field (the page will return an error if the requirement for the respective field is not met), and its type, i.e., if it is a required field or not.

On the registration page, the gender field will be presented as a select option, and hence the requirement is set as “Must select one” while the comment field is a text field and there’s no requirement set for it.

Now create an HTML form with the above fields.

How to Write the Code for PHP Form Validation?

The following code will create a form with the fields mentioned above and also validate the form. 

Some essential variables used in the code:

$_POST: It is a superglobal variable in PHP, which is used to collect data submitted in the form. It is also used to pass variables.

$_SERVER[“REQUEST_METHOD”]: This is also a super global variable that returns the request method used to access the page.

<!DOCTYPE HTML>  <html><head>    <style>        .error {color: #FF0000;}    </style></head><body>      <?php        $nameErr = $emailErr = $genderErr = $websiteErr = "";        $name = $email = $gender = $comment = $website = "";        if ($_SERVER["REQUEST_METHOD"] == "POST") {        if (empty($_POST["name"])) {            $nameErr = "Please enter a valid name";        } else {            $name = test_input($_POST["name"]);            // check if name only contains letters and whitespace            if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {            $nameErr = "Only letters and white space allowed";            }        }        if (empty($_POST["email"])) {            $emailErr = "valid Email address";        } else {            $email = test_input($_POST["email"]);            // check if e-mail address is well-formed            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {            $emailErr = "The email address is incorrect";            }        }          if (empty($_POST["website"])) {            $website = "";        } else {            $website = test_input($_POST["website"]);            // check if URL address syntax is valid            if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {            $websiteErr = "Enter a valid Webiste URL";            }            }        if (empty($_POST["comment"])) {            $comment = "";        } else {            $comment = test_input($_POST["comment"]);        }                if (empty($_POST["gender"])) {            $genderErr = "Please select a gender";        } else {            $gender = test_input($_POST["gender"]);        }        }        function test_input($data) {        $data = trim($data);        $data = stripslashes($data);        $data = htmlspecialchars($data);        return $data;        }    ?>    <h2>PHP Form Validation Example</h2>    <p><span class="error">* required field</span></p>    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">          FullName: <input type="text" name="name">        <span class="error">* <?php echo $nameErr;?></span>        <br><br>        E-mail address: <input type="text" name="email">        <span class="error">* <?php echo $emailErr;?></span>        <br><br>        Website: <input type="text" name="website">        <span class="error"><?php echo $websiteErr;?></span>        <br><br>        Comment: <textarea name="comment" rows="2" cols="10"></textarea>        <br><br>        Gender:        <input type="radio" name="gender" value="female">Female        <input type="radio" name="gender" value="male">Male            <span class="error">* <?php echo $genderErr;?></span>        <br><br>        <input type="submit" name="submit" value="Submit">      </form>    <?php        echo "<h2> Final Output:</h2>";        echo $name;        echo "<br>";        echo $email;        echo "<br>";        echo $website;        echo "<br>";        echo $comment;        echo "<br>";        echo $gender;    ?></body></html>

Next up, first, give incorrect details and see what the output will be.

form_validation_wrong_details_1

Now, if the correct details are entered, no error is displayed.

form_right_details_validation_2

Now that you have the code for the PHP form, you need to understand the different parts of the code used for the validation process.

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

Code Explanation by Parts

Let us begin by understanding some variables and functions used in the code.

$_SERVER[“PHP SELF”] Variable

$_SERVER[“PHP SELF”] variable is responsible for sending the form data submitted to the page itself. This means that the error messages and data in the form can be displayed on the same page as shown in the output above.

htmlspecialchars() Function

htmlspecialchars() converts special characters such as “&”(ampersand) into HTML entities “&amp”. This function protects the code from attackers.

Name Validation

if (empty($_POST["name"])) {            $nameErr = "Please enter a valid name";        } else {            $name = test_input($_POST["name"]);            // check if name only contains letters and whitespace            if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {            $nameErr = "Only letters and white space allowed";c            }

It uses this part of the code for name validation in the form.

Here, in the if statement, it checks whether the field is empty. If true, it displays an appropriate error message.

While the else statement checks whether any character (other than letters and whitespaces) is present in the entry or not, and displays an error message accordingly.

Email Validation

if (empty($_POST["email"])) {            $emailErr = "valid Email address";        } else {            $email = test_input($_POST["email"]);            // check if e-mail address is well-formed            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {            $emailErr = "The email address is incorrect";            }

In the above code, filter_var() is a function used to validate and filter user input data.

Further, FILTER_VALIDATE_EMAIL validates the value for being a valid email address.

Website Validation

if (empty($_POST["website"])) {            $website = "";        } else {            $website = test_input($_POST["website"]);            // check if URL address syntax is valid            if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {            $websiteErr = "Enter a valid Webiste URL";            }

Here, a preg_match() function is used which returns ‘true’ if a match (for the given set of patterns passed inside it) was found in a string.

It checks if the website string contains a valid URL.

Gender Validation

if (empty($_POST["gender"])) {            $genderErr = "Please select a gender";        } else {            $gender = test_input($_POST["gender"]);        }

Since the gender field has been displayed as a select option (i.e., Male or Female), this code only checks if an option is chosen or not.

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Conclusion

This brings us to the end of the “PHP Form Validation” tutorial. In this demo, you created a registration form for validation with the help of PHP. Later, you explored each section of the code used for the validation process separately.

Are you planning to take the plunge and do a course on PHP? In that case, Simplilearn’s PHP course would be an excellent choice. The Full Stack Developer - MERN Stackcovers all the fundamental and advanced concepts in PHP, making your journey towards learning PHP an easy one.

If you have any queries regarding the PHP Form Validation Article, please ask away in the comments section of this article, and we’ll have our experts answer them for you.

Stay safe and happy learning! 

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.