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!