Broad Network


PHP Form Simple Validation with embedded Error Messages from Server

Basics of PHP – Part 17

Forward: In this part of the series I talk about PHP Form Simple Validation with embedded Error Messages from Server

By: Chrysanthus Date Published: 29 Jul 2012

Introduction

This is part 17 of my series, Basics of PHP. When a user fills in a web page form, he might make syntax errors in the datum he types. For example, he might type a URL and forget to type the colon that precedes the two forward slashes. He might also type the email address without putting the @ sign. Any such URL or email typed is invalid, and cannot serve any purpose. Would it not be nice, if your PHP code at the server checks this and if there is an error, sends a feedback message to the user indicating to him that there is an error? In this article I will show you how the error message can be sent back to the same web page at the browser; each form control field receives its error message just above itself.

Validation means you check if the syntax of a datum is correct; if it is not correct you take action to correct it. So if a user types a datum in a form field and receives a message that the datum is not correct, he has to retype it making the correction.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Simple String Validation
Validating a string value, such as a user ID can be demanding. A simple validation would simply detect whether a string value was typed or not. This is what I show you here. Consider the following code:

    <?php
        $name = "a name";

        if ($name == "")
            {
                echo "The Name Field cannot be empty";
            }
        else
            echo "Do something with the value in the $_POST or $_GET array.";
        
    ?>

Read and try the above code. We have the variable, $name with a string value assigned to it. In actual validation this value will be input value from a form field. After this variable declaration, you have an if-statement. The if-condition, checks if the string variable is empty with ($name == ""). If it is empty, the if-statement echoes the error message. Else it does something with the form field value which should now be in the $_POST or $_GET array. Assign the empty string, "" to the $name variable and re-run the above code to see the result. I have not yet shown you how to make the error message appear just above the form field.

Note; the backslash that precedes the $ sign for the “$_POST” or “$_GET” word, makes the variable to be printed as such without being converted to the values, since we are dealing with a double quoted string.

The filter_var Function
The filter_var function is used to do validation of some obvious datum like the email address and the URL. It is a predefined function. You do not have to write any code to check if the email or URL syntax is correct. To validate an email, what you need for the function is the text, FILTER_VALIDATE_EMAIL, called the email filter ID. To validate a URL, what you need for the function is the text, FILTER_VALIDATE_URL, called the URL filter ID.

In simple terms, the syntax of the filter_var function is:

    mixed filter_var ( mixed $variable [int $filter ] )

The function can return a value of any type; that is why you have, mixed, as the return value in the syntax. Two parameters go into the parentheses. The second one is optional, but I advise you to always use it. The first parameter is for the value (integer, float or string) that is to be validated. The second parameter is for the filter ID.

The return value is actually the datum (email or URL) or false if the syntax of the datum is wrong. If the syntax is correct, the datum is returned, and that is equivalent to true. If the syntax is wrong the return value is false. So, you can use the filter_var function in the condition of an if-statement.

Validating an Email Address in PHP
Read and try the following code:

    <?php

        $email = "mymane@aserver.com";

        if(!filter_var($email, FILTER_VALIDATE_EMAIL))
            {
                 echo("The email address is not correct!");
            }
        else
             echo "Do something with the value in the $_POST or $_GET array.";
        
    ?>

The first line in the code is the declaration of a variable, with an email address in string form assigned to the variable. The syntax of this email address is correct. Then you have the if-statement. In the if-statement, you have the following function preceded by an exclamation sign, which is the NOT operator.

    filter_var($name, FILTER_VALIDATE_EMAIL)

As you can see, the first argument of the function is the string value of the email address. The second argument is the email filter ID. With these arguments, this predefined function will check if the syntax of the email address is correct. If it is correct, it returns the email address, which is equivalent to true. The NOT operator, preceding the function turns this into false, and so the else part of the if-statement is executed. If the validation returns false, meaning the syntax of the email address is wrong, then the if-part (true) of the if-statement will be executed, as the function will return false.

Remove the @ sign from the value of the variable and re-try the code; note that the if-part of the if-statement is executed.

Validating a URL Address in PHP
The process is similar to that of the email, but this time you use the FILTER_VALIDATE_URL filter ID instead. Read and try the following code:

    <?php

        $url = "http://www.cool-mathematics.com";

        if(!filter_var($url, FILTER_VALIDATE_URL))
            {
                 echo("The URL is not correct!");
            }
        else
             echo "Do something with the value in the $_POST or $_GET array.";
        
    ?>

Now, remove the colon from the URL and re-try the code.

Form Example
We shall use the following form to illustrate the validation of a web page form:

    <form method="post" action="myfile.php"> <br /><br />
        Name: <input type="text" name="userName"> <br /><br />
        Email: <input type="text" name="email"> <br /><br />
        Your Web Site URL: <input type="text" name="url"> <br /><br />
        Message: <textarea name="msg" rows="3" cols="30"></textarea>
    </form>

In your commercial project, you will have to do some more presentation than what I have done. If the syntax of a field is wrong, the error message will appear above it in red color. There will be one main error message that will always appear at the top of all the fields if any field has an error. To achieve this, you can put an HTML paragraph element with display property set to none. This paragraph element has the main error message. This paragraph will be displayed by JavaScript code.

The PHP programmer must know the names of the field controls, which would be in the $_POST array, after the form has been submitted. Each field will have a PHP script above it that would display an error message corresponding to the field content, if the syntax of the field content were wrong. Each code above the field will use the name of the field control to check if the field has an error.

The HTTP method value is POST, for our example. So at the server the PHP $_POST predefined array will hold the name/value pairs of the form controls as key/value pairs. The value of the action above, has the shorten URL, myfile.php. This is the file name of the HTML file at the server. If you want PHP to send any information to the web page having a form and the PHP code, the web page at the server should have the same file name as the file name in the URL of the action attribute. In this way, at the browser, the page having the form will simply call itself. When it calls itself, the any code in the page at the server will be executed and echo any message it has to echo at the position of the page, where the code is.

Let us now look at the whole code for our example.

A Simple Web page at server
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>

    <form method="post" action="myfile.php">

        <p id="P1" style="color:red; display:none">One or more Field Content is not correct!</p>

        <?php
                if ($_POST["userName"] == "")
                    {
                        echo "<span style='color:red' name='PHPSpan'>The Name Field cannot be

empty!</span><br />";
                    }      
        ?>
        Name: <input type="text" name="userName"> <br /><br />

        <?php
            if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
                {
                    echo "<span style='color:red' name='PHPSpan'>The Email Field Content is not

correct!</span><br />";
                }      
        ?>
        Email: <input type="text" name="email"> <br /><br />

        <?php
            if (!filter_var($_POST["url"], FILTER_VALIDATE_URL))
                {
                    echo "<span style='color:red' name='PHPSpan'>The URL Field Content is not

correct!</span><br />";
                }      
        ?>
        Your Web Site URL: <input type="text" name="url"> <br /><br />

        <?php
            if ($_POST["msg"] == "")
                {
                    echo "<span style='color:red' name='PHPSpan'>The Message Field cannot be

empty!</span><br />";
                }      
        ?>
        Message: <textarea name="msg" rows="3" cols="30"></textarea><br /><br />

        <button type="submit">Send</button>
    </form>

        <script type="text/javascript">
            spanRef = document.getElementsByName('PHPSpan');
            if (spanRef.length > 0)
                document.getElementById('P1').style.display = "block";  
        </script>

</body>
</html>

Read and try the above code. The JavaScript code is at the bottom. It checks if any of the span elements having PHP error message was sent. The PHP scripts send the error messages in span elements. If any were sent, the JavaScript would display the Paragraph element, which has the generalized error message.

Note that for the PHP scripts, the echo strings for the SPAN elements are delimited by double quotes. The attributes in the SPAN text are delimited by single quotes in order not to contradict the delimiters of the echo string. The rest of the code should be self-explanatory.

We have done a lot. Let us end here and continue in the next part of the series.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message