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;
}

?>

Series Navigation<< PHP Form Validation: Alter a value in $_Post
PHP Form Validation: Email addresses >>

Leave a comment

Leave a Reply