Code Snippets

Form Validation & Progressive Enhancement

For the ‘Contact’ form on the homepage of this portfolio site, I chose to dig deeply into form validation techniques, using a combination of browser-native validation and additional JavaScript.

HTML5 provides the ‘Constraint Validation API’, which specifies input types for basic pre-built input validation, and further custom validation with the ‘pattern’ attribute — via ‘regular expression’ (‘regex’).

I used ‘progressive enhancement’ to ensure data validation is always provided on the frontend, even if JavaScript is not available in the user’s browser, but additional validation feedback is provided if JavaScript is available to improve the form’s user experience (UX).

The form fields themselves use the required attribute, with regex provided in the pattern attribute.

This design pattern still supports optional form fields, as demonstrated by the phone number field.


<div id="contact" class="contact-form">
    <form id="contact-form" action="#">

        <h2>Get In Touch</h2>
        <div class="contact-form__validation-event-delegator">
            <div class="contact-form__input-group">
                <label for="contact-form-name">Name</label>
                <input type="text" id="contact-form-name" name="name" required
                    placeholder="What's your name?">
                <span class="contact-form__error-indicator contact-form__error-indicator--hidden">Don't forget to leave your name</span>
            </div>

            <div class="contact-form__input-group">
                <label for="contact-form-email">Email</label>
                <input type="email" id="contact-form-email" name="email" required
                    pattern="^[a-zA-Z0-9._\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,6}$"
                    placeholder="What's your email address?">
                <span class="contact-form__error-indicator contact-form__error-indicator--hidden">Don't forget to leave your correct email address</span>
            </div>

            <div class="contact-form__input-group">
                <label for="contact-form-phone">Phone <i>(optional)</i></label>
                <input type="tel" id="contact-form-phone" name="phone"
                    pattern="(\+?\d{1,4}[\s\-]?)?(\(?[\d\s\-]{1,}?\)?[\s\-]?)?[\d\s\-]{5,15}"
                    placeholder=" What's your phone number?">
                <span class="contact-form__error-indicator contact-form__error-indicator--hidden">Your phone number seems miss-typed</span>
            </div>

            <div class="contact-form__input-group">
                <label for="contact-form-message">Message</label>
                <textarea id="contact-form-message" name="message" required
                    placeholder="What would you like to say?"></textarea>
                <span class="contact-form__error-indicator contact-form__error-indicator--hidden">Don't forget to leave a message</span>
            </div>
        </div>
        <div class="contact-form__input-group">
            <button type="submit">Submit</button>
        </div>

    </form> 
</div>

In a linked JavaScript file, a combination of event listeners and utility functions provide a more comprehensive UX. We start by abstracting the actual logic of how to show & hide the ‘error indicators’ underneath each form field (which is done using a class with display: none):


/* Utility functions to handle updating 'strong' signified state of form fields */

function showErrorIndicator(inputField) {
    inputField.parentElement.querySelector('.contact-form__error-indicator').classList.remove('contact-form__error-indicator--hidden');
}

function hideErrorIndicator(inputField) {
    inputField.parentElement.querySelector('.contact-form__error-indicator').classList.add('contact-form__error-indicator--hidden');
}
                    

I used two levels of feedback: ‘hard’ and ‘soft’. Soft is for inline, hard is on a field-by-field basis. We do this because we want to give the user immediate feedback while they are typing about whether the data they are providing will be accepted, but we understand that they haven’t actually finished typing yet. When the user navigates away from the form field, we want to give them ‘hard’ feedback so they can correct their input as they go, instead of having to do it all when they try to submit the form. This approach attempts to maximise useful feedback to the user without distracting or overloading them.

I created utility classes to manage these ‘hard’ feedback states, to abstract the inner workings:


// Signify value is definitely valid 
function indicateHardValid(inputField) {
    inputField.classList.add('contact-form__input-field--definitely-valid');
}

// Signify value needs changing before submission
function indicateHardInvalid(inputField) {
    inputField.classList.add('contact-form__input-field--needs-changing');
}

// Remove strong visual signifiers on the form field
function removeHardValidate(inputField) {
    inputField.classList.remove('contact-form__input-field--definitely-valid', 'contact-form__input-field--needs-changing', 'contact-form__input-field--presubmission-invalid');
    hideErrorIndicator(inputField);
}
                    

Next we add event listeners to the form itself. There are lots of different ways to do this, but for this form I created a <div> element that is ‘delegated’ event listeners for multiple form fields — rather than creating a separate event listener for each field.

We want to use the in-built, native Element.checkValidity() method, which is part of the ‘Constraint Validation API’ mentioned earlier. This checks whether the value of a field is valid, using the default type validation and other additional parameters that we can set as attributes in the HTML — remember: we want our form to validate to a minimum baseline even without JavaScript.


/* Event listeners for additional validation */

// Grab the contact form
const contactForm = document.querySelector('form#contact-form');
// Grab the <div> that contains form fields but not the submit <button>
const eventDelegatorDiv = contactForm.querySelector('.contact-form__validation-event-delegator');

// Per-field validation bound to 'focusout' event on form fields
eventDelegatorDiv.addEventListener('focusout', event => {
    
    if (event.target.checkValidity()) {
        indicateHardValid(event.target);
        hideErrorIndicator(event.target);
    }
    // Don't need an Else clause here, 
    // because `event.target.checkValidity()` causes an 'invalid' event if false
});

// If the user returns to a form field 
eventDelegatorDiv.addEventListener('focusin', event => {
    
    // Remove strong visual signifiers on the form field
    removeHardValidate(event.target);
});
                    

‘invalid’ events do not ‘bubble’ up the DOM, so we need to switch our event listener to trigger on the ‘capture phase’ instead.


// Overwrite the existing 'invalid' event with custom functionality
eventDelegatorDiv.addEventListener('invalid', event => {

    // Prevent the browser-native feedback bubbles from appearing
    event.preventDefault();

    // Signify invalid value needs changing
    indicateHardInvalid(event.target);
}, {
    // Capture-phase event, not a bubble-phase event
    capture: true
});
                    

In order to make use of the form’s ‘submit’ event, we give the form a ‘novalidate’ attribute. It’s important we do this in our JavaScript instead of our HTML to fit with our ‘progressive enhancement’ approach.

We can include additional ‘pre-submission’ validation rules in this ‘submit’ event handler. Using ‘submit’ on the form, instead of ‘click’ on the button, means pressing enter on a text input still triggers a ‘submit’ event. By using an If statement, bound to contactForm.checkValidity(), we are essentially 'rebuilding' the original browser-native constraint validation, but now we can customise it to our liking (or business logic).


// Deactivate default pre-submission validation behaviour
// (Browser native validation will still occur if JavaScript is disabled)
contactForm.setAttribute('novalidate', true);

// Final pre-submission validation
contactForm.addEventListener('submit', event => {

    if (!contactForm.checkValidity()) {

        // Manually prevent the form from submitting
        event.preventDefault();
        
        contactForm.querySelectorAll(':invalid').forEach(invalidField => {
            // Add a red border around each invalid field
            invalidField.classList.add('contact-form__input-field--presubmission-invalid');
            // Show the error indicator underneath each invalid field
            showErrorIndicator(invalidField);
        });

        // Ensure focus goes to the first invalid form field
        const nextInvalidFieldToFillIn = contactForm.querySelectorAll(':invalid')[0];
        nextInvalidFieldToFillIn.focus();
        showErrorIndicator(nextInvalidFieldToFillIn);

    } else {
        // If validation passes, submit the form!
        contactForm.submit();
    }
});
                    

In our SCSS, we can assign a variety of styling rules to handle ‘live’ validation. I’ve named the modifier classes after what they are designed to signify in the mind of the user.


// Input is being used and value is not valid
input:not(:placeholder-shown):invalid,
textarea:not(:placeholder-shown):invalid {
    border-color: $soft-alert-orange;
}

// Input has been used and value is invalid
input:not(:placeholder-shown).contact-form__input-field--needs-changing,
textarea:not(:placeholder-shown).contact-form__input-field--needs-changing {
    border-color: $hard-alert-red;
}

// Input is being used
input:focus,
textarea:focus {
    outline: none;
    border-color: $feedback-yellow;
}

// Input is being used and input given will be valid 
input:not(:placeholder-shown):valid,
textarea:not(:placeholder-shown):valid {
    border-color: $soft-success-green;
}

input:not(:placeholder-shown).contact-form__input-field--definitely-valid,
textarea:not(:placeholder-shown).contact-form__input-field--definitely-valid {
    border-color: $hard-success-green;
}

// Input can't be submitted until the value is valid
input.contact-form__input-field--presubmission-invalid,
textarea.contact-form__input-field--presubmission-invalid {
    border-color: $hard-alert-red;
}
                    

This approach attempts adding a modular, maintainable, but flexible and potentially very sophisticated set of UX features to the webform, while maintaining ‘good-enough’ data validation even without JavaScript!

Capturing, Validating, and Storing Form Input

The contact form on the homepage of this portfolio site uses PHP to process messages sent through the contact form.

First, the browser sends an HTTP GET request to the same URI as the page with the form — the homepage, the index of the site. This keeps things tidy, and means our server-side code is at the top of index.php.

We’ll be using session variables, so we can persist data across a ‘Post/Redirect/Get’ pattern.


<?php

// Start/resume session to use session variables
session_start();

We’ll get the submitted form data out of the body of the POST request using PHP’s built-in superglobals:


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Set session variables & sanitiase input data
    $_SESSION['name'] = trim(htmlspecialchars($_POST['name']));
    $_SESSION['email'] = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    $_SESSION['phone'] = preg_replace('/\D/', '', $_POST['phone']);
    $_SESSION['message'] = trim(htmlspecialchars($_POST['message']));
                    

FILTER_SANITIZE_STRING is deprecated as of PHP 8.1.0, so I’ve used htmlspecialchars() (the recommended alternative) instead.

Once we know that our form data is sanitised (it only contains characters we allow and expect), we can move on to validating the result of our santisation. The If statement checks if the sanitised inputs are invalid, and if so updates a session variable to hold an ‘error’ state:


$phoneValidationPattern = "/(\+?\d{1,4}[\s\-]?)?(\(?[\d\s\-]{1,}?\)?[\s\-]?)?[\d\s\-]{7,15}/";

if (
        empty($_SESSION['name'])
        || empty($_SESSION['email'])
        // Phone number either passess the regex or is not provided
        || (!preg_match($phoneValidationPattern, $_SESSION['phone']) && !$_SESSION['phone'] === '')
        || empty($_SESSION['message'])
    ) {
        $_SESSION['error'] = true;

        // Redirect to the form, so the user can try again 
        header('Location: index.php#contact-form');
        exit();
    } else {
        // Send data to database
                    

Assuming the data is not invalid, we can add it to the SQL database! To do this, we will be including another file so we can call a function declared inside — separating the PHP file that displays and handles submission of the form in one file, and declaring ‘helper’ functions in another, is a good practice and represents a ‘separation of concerns’.


include_once 'lib/add-message-to-database.php'; 
                                

I like to use very descriptive variable and function names! Let’s have a look at addMessageToDatabase()


<?php

function addMessageToDatabase(array $message): bool
{
    // Get `$databaseConnection` from `lib/database-connection.php`
    include 'database-connection.php';

    try {
        $pdoStatement = $databaseConnection->prepare('
        INSERT INTO Messages (name, email, phone, message)
        VALUES (:name, :email, :phone, :message)
        ');

        $pdoStatement->bindValue(':name', $message['name'], PDO::PARAM_STR);
        $pdoStatement->bindValue(':email', $message['email'], PDO::PARAM_STR);
        $pdoStatement->bindValue(':phone', $message['phone'], PDO::PARAM_STR);
        // If the phone number is an empty string, set it to PHP's `null` instead, 
        // so SQL will save it as it's own `NULL` data type.
        $pdoStatement->bindValue(
            ':phone',
            $message['phone'] === '' ? null : $message['phone'],
            PDO::PARAM_STR
        );
        $pdoStatement->bindValue(':message', $message['message'], PDO::PARAM_STR);

        // Execute the SQL command
        $pdoStatement->execute();

        // If successful, return true for frontend UI feedback
        return true;
    } catch (Exception $exception) {
        echo "Database query failed: " . $exception->getMessage();
        return false;
    }
}
                    

This function encapsulates the logic for creating a SQL query that adds the form data to the database. I’ve used a ‘prepared statement’ to avoid accidental SQL injection, which is an attack vector that could be used by a malicious actor to damage the integrity of the database.

Setting up the actual database connection is done in another separate file:


<?php

include 'get-env-variable.php';

$server = getEnvironmentalVariable('SERVER');
$database = getEnvironmentalVariable('DATABASE');
$user = getEnvironmentalVariable('USER');
$password = getEnvironmentalVariable('DATABASE_PASSWORD');

if ($password === false) {
    echo 'Database password not found in .env file';
    exit;
}

try {
    $databaseConnection = new PDO("mysql:host=$server;dbname=$database", $user, $password);
} catch (PDOException $exception) {
    echo 'Database connection failed: ' . $exception->getMessage();
    exit;
}
                    

I’ve used another helper function here to get the environmental variables from a .env file; this approach crucially avoids exposing credentials in version control repositories, and means the same project code works locally and in production.

The getEnvironmentalVariable() function works by accessing the .env file and checking through to find the line with a key that corresponds to the environmental variable requested. If this line is found, it’ll return the value of the environmental variable — it’ll return false if not, which means I can easily evaluate against its return value in conditionals.

I’ve used type declarations in this function make it clear what arguments it expects and which type of value will return:


<?php

function getEnvironmentalVariable(string $variableName): string|bool
{
    // Get the entire `.env` file as a string
    $contents = file_get_contents(__DIR__ . '/../../.env');

    // Split the string into an array of lines
    $lines = explode("\n", $contents);

    foreach ($lines as $line) {

        // If the line contains the requested environmental variable
        if (strpos($line, $variableName) !== false) {

            // Get the value and return it
            $explodedLine = explode('=', $line);
            return $explodedLine[1];
        }
    }
    // Return false if the environmental variable was not found
    return false;
}
                    

To connect to the MariaDB / MySQL database running either on my local device or the production server, I’ve used PHP’s PDO (‘PHP Data Object’) built-in functionality, which is generally recommended.

Returning to index.php, we add a session variable to set application state as successful for the form submission, reset our session variables for the form fields (so the previous form data is not still be shown in the form fields, confusing the user), and then redirect the client again to clear any data from the body of the HTTP request (to prevent form data being submitted twice if the page is refreshed by the user).


// Pass the message data as an associative array to be stored in the database, 
// and evaluate if this was successful
if (addMessageToDatabase(
    [
        'name' => $_SESSION['name'],
        'email' => $_SESSION['email'],
        'phone' => $_SESSION['phone'],
        'message' => $_SESSION['message']
    ]
)) {
    $_SESSION['success'] = true;

    // Reset session variables
    $_SESSION['name'] = $_SESSION['email'] = $_SESSION['phone'] = $_SESSION['message'] = '';
} else {
    // Set error message
    $_SESSION['error'] = true;
}
// Follow Post/Redirect/Get pattern to avoid resubmitting the form on refresh
header('Location: index.php');
exit();
}
                            

The form data would otherwise be repopulated using the value attribute of the <input> element:


<input 
    type="text" 
    id="contact-form-name" 
    name="name" 
    required 
    placeholder="What's your name?" 
    value="<?php
        if (isset($_SESSION['name'])) {
            echo $_SESSION['name'];
        }
    ?>">
                            

I used some <script> tags at the bottom of the file in combination with additional JavaScript in a linked file to offer some final user feedback on the success or failure of the form submission. This code will run in relation to the server-side logic, so it marries server-side validation with front-end feedback.


<?php
// If the form has just been submitted, provide a visual indicator of success
if (isset($_SESSION['success']) && $_SESSION['success'] === true) {
    echo '<script>createFormSuccessIndicator();</script>';
    // Reset session variable to avoid the indicator being shown on refresh
    $_SESSION['success'] = false;
}

// If the form data has failed server-side validation, provide a visual indicator of the error
if (isset($_SESSION['error']) && $_SESSION['error'] === true) {
    echo '<script>createFormSubmissionFailIndicator();</script>';
    // Reset session variable to avoid the indicator being shown on refresh
    $_SESSION['error'] = false;
}
?>