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( ).


// 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()) {
    } else {
} else {

// 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'>
Your email: <input type='text' name='email'>
<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>

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


CSS3 Selectors: :required & :optional

This entry is part 23 of 40 in the series CSS3 Selectors

We might want to highlight a form field where the users will have to fill up.


Applies to form controls that have the <required> attribute set.


Applies to all form controls that do not have the <required> attribute.

Quick contact form

<!DOCTYPE html>
<html lang='en'>
    <meta charset='utf-8'>
    <title>Quick contact form</title>
        input:required {
            border: 1px solid red;
        input:optional {
            border: 1px solid blue;
        <legend>Contact information</legend>
                <label for='email'>Email:</label>
                <input required type='email' id='email' name='email'/>
                <label for='tel'>Telephone number:</label>
                <input type='tel' id='tel' name='tel'/>
                <label for='url'>Website:</label>
                <input type='url' id='url' name='url'/>
        <input type='submit' value='Submit this' />