PHP Form Validation: Email addresses

This entry is part 7 of 7 in the series PHP Form Validation

Checking an email address is arguably the most common form validation task for a form.

A common method is to use regular expression.

The regular expression ^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$ matches most common email addresses and fails to match common mistypings of addresses.

Use it with preg_match( ) as shown below.

<?php

// Logic to do the right thing based on
// the hidden submit_check parameter
if ($_POST['submit_check']) {
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    } else {
        process_form();
    }
} else {
    show_form();
}

// Do something when the form is submitted
function process_form()
{
    print 'Hello, ' . $_POST['email'];
}

// Display the form
function show_form($errors = '')
{
    // If some errors were passed in, print them out
    if ($errors) {
        print 'Please correct these errors: <ul><li>';
        print implode('</li><li>', $errors);
        print '</li></ul>';
    }

    print <<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>

Your email: <input type='text' name='email'>
<br>

<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>
</form>
html_output;
}

// Check the form data
function validate_form()
{
    // Start with an empty array of error messages
    $errors = array();
    // Add an error message if the name is too short
    if (!preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $_POST['email'])) {
        $errors[] = 'Please enter a valid e-mail address';
    }
    // Return the (possibly empty) array of error messages
    return $errors;
}

?>

PHP Form Validation: Number ranges

This entry is part 6 of 7 in the series PHP Form Validation

To check whether a number falls within a certain range, first make sure the input is a number.

if ($_POST['age'] != strval(intval($_POST['age']))) {
    $errors[0] = "Your age must be a number.";
} elseif (($_POST['age'] < 18) || ($_POST['age'] > 65)) {
    $errors[0] = "Your age must be at least 18 and no more than 65.";
}

Then, use an if() statement to test the value of the input.

<?php

// Logic to do the right thing based on
// the hidden submit_check parameter
if ($_POST['submit_check']) {
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    } else {
        process_form();
    }
} else {
    show_form();
}

// Do something when the form is submitted
function process_form()
{
    print 'Your Age is, ' . $_POST['age'];
}

// Display the form
function show_form($errors = '')
{
    // If some errors were passed in, print them out
    if ($errors) {
        print 'Please correct these errors: <ul><li>';
        print implode('</li><li>', $errors);
        print '</li></ul>';
    }

    print <<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>

Your Age: <input type='number' name='age'>
<br>
<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>
</form>
html_output;
}

// Check the form data
function validate_form()
{
    // Start with an empty array of error messages
    $errors = array();

    if ($_POST['age'] != strval(intval($_POST['age']))) {
        $errors[0] = "Your age must be a number.";
    } elseif (($_POST['age'] < 18) || ($_POST['age'] > 65)) {
        $errors[0] = "Your age must be at least 18 and no more than 65.";
    }
    // Return the (possibly empty) array of error messages
    return $errors;
}

?>

PHP Form Validation: Required elements

This entry is part 2 of 7 in the series PHP Form Validation

Required elements are common in input form.

If there is a field in the input form that is required, we can check the element’s length with strlen( ).

<?php

// Logic to do the right thing based on
// the hidden submit_check parameter
if ($_POST['submit_check']) {
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    } else {
        process_form();
    }
} else {
    show_form();
}

// Do something when the form is submitted
function process_form()
{
    print 'Hello, ' . $_POST['my_name'];
}

// Display the form
function show_form($errors = '')
{
    // If some errors were passed in, print them out
    if ($errors) {
        print 'Please correct these errors: <ul><li>';
        print implode('</li><li>', $errors);
        print '</li></ul>';
    }

    print <<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>
Your name: <input type='text' name='my_name'>
<br/>
Your email: <input type='text' name='email'>
<br>
<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>
</form>
html_output;
}

// Check the form data
function validate_form()
{
    // Start with an empty array of error messages
    $errors = array();

    // Add an error message if the name is too short
    if (strlen($_POST['my_name']) < 3) {
        $errors[0] = 'Your name must be at least 3 letters long.';
    }
    if (strlen($_POST['email']) == 0) {
        $errors[1] = "You must enter an email address.";
    }

    // Return the (possibly empty) array of error messages
    return $errors;
}

?>

PHP Form Validation: Displaying error messages with form

This entry is part 1 of 7 in the series PHP Form Validation

Form validation is important as users could be careless with the data they have entered into the form.

We need to display some error messages when users have entered them incorrectly.

We use here a different method to display an error message as compare to an earlier post.

<?php

// Logic to do the right thing based on
// the hidden submit_check parameter
if ($_POST['submit_check']) {
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    } else {
        process_form();
    }
} else {
    show_form();
}

// Do something when the form is submitted
function process_form()
{
    print 'Hello, ' . $_POST['my_name'];
}

// Display the form
function show_form($errors = '')
{
    // If some errors were passed in, print them out
    if ($errors) {
        print 'Please correct these errors: <ul><li>';
        print implode('</li><li>', $errors);
        print '</li></ul>';
    }

    print <<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>
Your name: <input type='text' name='my_name'>
<br/>
<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>
</form>
html_output;
}

// Check the form data
function validate_form()
{
    // Start with an empty array of error messages
    $errors = array();

    // Add an error message if the name is too short
    if (strlen($_POST['my_name']) < 3) {
        $errors[] = 'Your name must be at least 3 letters long.';
    }

    // Return the (possibly empty) array of error messages
    return $errors;
}

?>

In line 23, $errors = ” is the default for $errors variable. It is an empty string and resolved to false and so if there is no variable, the form is always shown.

In line 28, we also use a common method implode to join an $errors array element with the string </li><li>.

PHP: A simple form with validation

This entry is part 41 of 54 in the series PHP Tutorial

This is a form with a simple validation function.

The validate_form( ) function returns false if $_POST[‘my_name’] is less than three characters long, and returns true otherwise.

<?php

// Logic to do the right thing based on
// the hidden _submit_check parameter
if (array_key_exists('submit_check', $_POST)) {
    if (validate_form( )) {
        process_form( );
    } else {
        show_form( );
        echo 'Name must be at least 3 characters long';
    }
} else {
    show_form( );
}

// Do something when the form is submitted
function process_form( ) {
    print 'Hello, '. $_POST['my_name'];
}

// Display the form
function show_form( ) {
    print<<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>
Your name: <input type='text' name='my_name'>
<br/>
<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>
</form>
html_output;
}

// Check the form data
function validate_form( ) {
    // Is my_name at least 3 characters long?
    if (strlen($_POST['my_name']) < 3) {
        return false;
    } else {
        return true;
    }
}

?>