Home > Tutorials > PHP Tutorials > How To Validate Form Data With PHP

How To Validate Form Data With PHP

Whenever you’re dealing with online forms it’s important to perform proper validation on the data that is submitted. Form validation ensures that the user will enter valid data on the form – minimizing your chances at possible SQL injections. PHP lets us perform server-side validation, and lets us display the appropriate error messages if a user enters incorrect values.

Required Fields

Required fields are the mandatory fields that must be filled out with our form. If the user does not enter a value in a required field, we have to show an error message to the user.

The following code example lets you make a text field a required field. The error message is stored in the variable ‘$err_address‘. The ‘empty()’ function checks if the input field is empty. The statement ‘<?php echo $err_address; ?>‘ displays the error message on the form.

<?php 
$err_address = "";

if($_SERVER["REQUEST_METHOD"]=="POST")
{
    if(empty($_POST["address"]))
    {
        $err_address = "Please enter your address. This field is mandatory.";
    }
}
?>

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<input type="text" name="address" placeholder="Enter your address.">
<?php echo $err_address; ?><br>
<input type="submit" value="Submit">
</form>

If the user does not enter any value in the text field, the error message ‘Please enter your address. This field is mandatory.’ will be displayed, as shown in the screenshot below.

Email Validation

You can check whether an email address is valid or not using the ‘filter_var()‘ function. In the code below, we have passed two argument values to this function. The first argument value is our email address while the second one is a predefined constant.

<?php 
$err_email = "";

if($_SERVER["REQUEST_METHOD"]=="POST")
{
   if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
    {
        $err_email = "Please enter a valid email address.";
    }
}
?>

The predefined constant ‘FILTER_VALIDATE_EMAIL‘ indicates that the ‘filter_var()‘ function will validate an email address.

URL Validation

The ‘filter_var()‘ function also allows you to check if a web URL is valid. In the code below, we have passed two argument values to this function. The first argument value is our website URL while the second one is a predefined constant.

<?php 
$err_url = "";

if($_SERVER["REQUEST_METHOD"]=="POST")
{
    if (!filter_var($_POST["url"], FILTER_VALIDATE_URL))
    {
        $err_url = "Please enter a valid web URL.";
    }
}
?>

The predefined constant ‘FILTER_VALIDATE_URL‘ indicates that the filter_var() function will validate a web URL. In the above code example, the URL is valid only if it is entered in this format: ‘https://www.mysite.com‘.

Name Validation

To validate a name, we have used this regular expression: ‘/^[a-zA-Z ]*$/‘ in the code below. The ‘preg_match()‘ function checks if the pattern specified in the regular expression exists in the second argument value, which is a string value. So in the code example below, this function checks if the specified pattern exists in the name.

<?php 
$err_name = "";

if($_SERVER["REQUEST_METHOD"]=="POST")
{
    if (!preg_match("/^[a-zA-Z ]*$/", $_POST["name"]))
    {
        $err_name = "Invalid name format! The name can contain letters and whitespaces only.";
    }
}
?>

In the example above, the entered name is valid if it contains only letters and whitespaces.

Password Validation

For password validation, we have used this regular expression: ‘/^.*(?=.{6,})(?=.*[0-9])(?=.*[A-Z]).*$/‘ in the code below, which specifies a particular password format. Use a different regular expression for a different password format.

<?php 
$err_password = "";

if($_SERVER["REQUEST_METHOD"]=="POST")
{
    if (!preg_match("/^.*(?=.{6,})(?=.*[0-9])(?=.*[A-Z]).*$/", $_POST["password"]))
    {
        $err_password = "The minimum length of your password must be 6 characters. Enter at least one capital letter and one number.";
    }
}
?>

In the example above, the password is valid if it is at least 6 characters long and if it contains at least one capital letter and at least one number.

Phone Number Validation

The code below validates a phone number. If the user enters the phone number in an invalid format, an error message is shown.

<?php 
$err_phone = "";

if($_SERVER["REQUEST_METHOD"]=="POST")
{
    if (!preg_match("/^[0-9]{10}/", $_POST["phone"]))
    {
        $err_phone = "Invalid phone number format! Please enter a 10-digit phone number.";
    }
}
?>

In the example above, a phone number is valid only if it is 10 digits long.

Postal Code/Zip Code Validation

The code below validates a postal code. If the user enters the postal code in an invalid format, an error message is shown. In the following example, a postal code is valid only if it is 6 digits long.

<?php 
$err_postal = "";

if($_SERVER["REQUEST_METHOD"]=="POST")
{
    if (!preg_match("/^[0-9]{6}/", $_POST["postal"]))
    {
        $err_postal = "Invalid postal code format! The postal code must be 6 digits long.";
    }
}
?>

In this article, you learned how to validate form data using PHP. Hopefully you’ve enjoyed this PHP tutorial. Feel free to leave any questions you might have in the comments section below.

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

Understanding PHP Constants

A constant within PHP is essentially an identifier for a simple value, and unlike a ...

Like every other website, this site uses cookies to deliver to analyze our traffic. Cookies may also be utilized by our advertisers and partners. By using this website you agree to the use of said cookies. More Information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings, continuing to navigate past this message, or you click "Accept" below then you are consenting to the use of cookies on the Rapid Purple website.

Close