Most JavaScript form validation libraries are large, and often require other libraries like jQuery. For example, MailChimp's embeddable form includes a 140kb validation file (minified). It includes the entire jQuery library, a third-party form validation plugin, and some custom MailChimp code. In fact, that setup is what inspired this new series about modern form validation. What new tools do we have these days for form validation? What is possible? What is still needed?
In this series, I'm going to show you two lightweight ways to validate forms on the front end. Both take advantage of newer web APIs. I'm also going to teach you how to push browser support for these APIs back to IE9 (which provides you with coverage for 99.6% of all web traffic worldwide).
Finally, we'll take a look at MailChimp's sign-up form, and provide the same experience with 28× less code.
It's worth mentioning that front-end form validation can be bypassed. You should always validate your code on the server, too.
Alright, let's get started!
Article Series:
- Constraint Validation in HTML (You are here!)
- The Constraint Validation API in JavaScript
- A Validity State API Polyfill
- Validating the MailChimp Subscribe Form
#The Incredibly Easy Way: Constraint Validation
Through a combination of semantic input types (for example,
<input type="email">
) and validation attributes (such as required
and pattern
), browsers can natively validate form inputs and alert users when they're doing it wrong.
Support for the various input types and attributes varies wildly from browser to browser, but I'll provide some tricks and workarounds to maximize browser compatibility.
#Basic Text Validation
Let's say you have a text field that is required for a user to fill out before the form can be submitted. Add the
required
attribute, and supporting browsers will both alert users who don't fill it out and refuse to let them submit the form.
Do you need the response to be a minimum or maximum number of characters? Use
minlength
and maxlength
to enforce those rules. This example requires a value to be between 3 and 12 characters in length.
The
pattern
attribute let's you run regex validations against input values. If you, for example, required passwords to contain at least 1 uppercase character, 1 lowercase character, and 1 number, the browser can validate that for you.
If you provide a
title
attribute with the pattern
, the title
value will be included with any error message if the pattern doesn't match.
You can even combine it with
minlength
and (as seems to be the case with banks, maxlength
) to enforce a minimum or maximum length.#Validating Numbers
The
number
input type only accepts numbers. Browsers will either refuse to accept letters and other characters, or alert users if they use them. Browser support for input[type="number"]
varies, but you can supply a pattern
as a fallback.
By default, the
number
input type allows only whole numbers.
You can allow floats (numbers with decimals) with the
step
attribute. This tells the browser what numeric interval to accept. It can be any numeric value (example, 0.1
), or any
if you want to allow any number.
You should also modify your
pattern
to allow decimals.
If the numbers should be between a set of values, the browser can validate those with the
min
and max
attributes. You should also modify your pattern
to match. For example, if a number has to be between 3 and 42, you would do this:#Validating Email Addresses and URLs
The
email
input type will alert users if the supplied email address is invalid. Like with the number
input type, you should supply a pattern for browsers that don't support this input type.
Email validation regex patterns are a hotly debated issue. I tested a ton of them specifically looking for ones that met RFC822 specs. The one used below, by Richard Willis, was the best one I found.
One "gotcha" with the the
email
input type is that it allows email addresses without a TLD (the "example.com" part of "email@example.com"). This is because RFC822, the standard for email addresses, allows for localhost emails which don't need one.
If you want to require a TLD (and you likely do), you can modify the
pattern
to force a domain extension like so:
Similarly, the
url
input type will alert users if the supplied value is not a valid URL. Once again, you should supply a pattern for browsers that don't support this input type. The one included below was adapted from a project by Diego Perini, and is the most robust I've encountered.
Like the
email
attribute, url
does not require a TLD. If you don't want to allow for localhost URLs, you can update the pattern to check for a TLD, like this.#Validating Dates
There are a few really awesome input types that not only validate dates but also provide native date pickers. Unfortunately, Chrome, Edge, and Mobile Safari are the only browsers that implement it. (I've been waiting years for Firefox to adopt this feature! Update: this feature should hopefully be coming to Firefox in the near future, too.) Other browsers just display it as a text field.
As always, we can provide a
The
pattern
to catch browsers that don't support it.The
date
input type is for standard day/month/year dates.
In supporting browsers, the selected date is displayed like this:
MM/DD/YYYY
(caveat: in the US. This can vary for users in other countries or who have modified their date settings). But the value
is actually in this format: YYYY-MM-DD
.
You should provide guidance to users of unsupported browsers about this format—something like, "Please use the YYYY-MM-DD format." However, you don't want people visiting with Chrome or Mobile Safari to see this since that's not the format they'll see, which is confusing.
#A Simple Feature Test
We can write a simple feature test to check for support, though. We'll create an
input[type="date"]
element, add a value that's not a valid date, and then see if the browser sanitizes it or not. You can then hide the descriptive text for browsers that support the date
input type.#Other Date Types
The
time
input type let's visitors select a time, while the month
input type let's them choose from a month/year picker. Once again, we'll include a pattern for non-supporting browsers.
The
time
input displays time in 12-hour am/pm format, but the value
is 24-hour military time. The month
input is displayed as May 2017
in supporting browsers, but the value is in YYYY-MM
format.
Just like with
input[type="date"]
, you should provide a pattern description that's hidden in supporting browsers.#This seems super easy. What's the catch?
While the Constraint Validation API is easy and light-weight, it does have some drawbacks.
You can style fields that have errors on them with the
:invalid
pseudo-selector, but you can't style the error messages themselves.
Behavior is also inconsistent across browsers. Chrome doesn't display any errors until you try to submit the form. Firefox displays a red border when the field loses focus, but only displays error messages on hover (whereas WebKit browsers keep the errors persistent).
User studies from Christian Holst and Luke Wroblewski (separately) found that displaying an error when the user leaves a field, and keeping that error persistent until the issue is fixed, provided the best and fastest user experience. Bonus CSS tip: style invalid selectors only when they aren't currently being edited with
:not(:focus):invalid { }
.
Unfortunately, none of the browsers behave exactly this way by default.
In the next article in this series, I'll show you how to use the native Constraint Validation API to bolt-in our desired UX with some lightweight JavaScript. No third-party library required!
Article Series:
- Constraint Validation in HTML (You are here!)
- The Constraint Validation API in JavaScript
- A Validity State API Polyfill
- Validating the MailChimp Subscribe Form
Comments
Post a Comment