Client-Side Form Validation with HTML5
When building web applications, it is important you take security seriously, especially when it has to do with collecting data from users.
It is a common maxim in security to trust nobody, hence never trust the user to enter correct or valid form values. For example, in an email form field, instead of entering a valid email address, the user might enter an invalid one or malicious data obviously ignoring the intent of the request.
When it comes to validating form values, it can be done on the client-side (web browser) and on the server-side (using your preferred server-side language).
In the past, client-side validation could only be achieved using JavaScript or using libraries from frameworks (think jQuery validation plugin). But that is changing or rather has changed because validation can now be done using HTML5 without having to write complex JavaScript validation code.
Form Validation with HTML5
HTML5 includes a fairly solid form validation mechanism powered by the following <input />
attributes: type
, pattern
, and require
. Thanks to these new attributes in HTML5, you can delegate some data verification functions to the browser.
Let’s examine these new form attributes to see how they can aid form validation.
The type
Attribute
This form attribute indicates what kind of input control to display such as the popular <input type="text" />
for handling simple text data.
Some form controls inherit validation systems without having to write any code. For example, <input type="email" />
validates the field to ensure the entered data is in fact a valid email address. If the field contains an invalid value, the form cannot be submitted for processing until it is corrected.
Try the demo below by entering an invalid email:
See the Pen Email Validation Example by SitePoint (@SitePoint) on CodePen.
There is also <input type="number" />
, <input type="url" />
and <input type="tel" />
for validating numbers, URLs, and telephone numbers respectively.
Note: The formatting of phone numbers varies from country to country due to the inconsistency in lengths and formats. As a result, the specification doesn’t define an algorithm for validating these, hence it isn’t supported web browsers at the time of writing.
Mind you, validation can be provided to tel
using the pattern
attribute which accepts a Regular Expression
string, and which we’ll consider next.
The pattern
Attribute
The pattern attribute will likely make a lot of developers, especially those working on the front-end, happy. This attribute specifies a format (in the form of a JavaScript Regular Expression) that the field value is checked against.
Regular expressions are a language used for parsing and manipulating text. They are often used to perform complex search-and-replace operations, and to ensure that text data is well-formed.
Today, regular expressions are included in most programming languages, as well as in many scripting languages, editors, applications, databases, and command-line tools.
Regular expressions (RegEX) provide a powerful, concise, and flexible means for matching strings of text such as particular characters, words, or patterns of characters.
By passing a RegEX string as the value for the pattern
attribute, you can dictate what value is acceptable by the form field and also inform the user of errors.
Let’s see some examples of using regular expressions for validating form field data.
Telephone numbers:
As mentioned, the tel
input type isn’t fully supported by web browsers due to the inconsistent format of telephone numbers across different countries.
For example, in my country, Nigeria, the telephone format is xxxx-xxx-xxxx
which would be something like 0803-555-8205.
The RegEX ^\d{4}-\d{3}-\d{4}$
matches the format hence the input element would look like this:
<label for="phonenum">Phone Number:</label>
<input type="tel" pattern="^\d{4}-\d{3}-\d{4}$" >
See the Pen Phone Number Validation Example by SitePoint (@SitePoint) on CodePen.
Alpha-Numeric Values
The following matches an alpha-numeric (combination of alphabets and numbers) character.
<input type="text" pattern="[a-zA-Z0-9]+" >
See the Pen Alpha-Numeric Character Validation Example by SitePoint (@SitePoint) on CodePen.
Twitter Username
This regular expression matches a Twitter username with the leading @ symbol. For example @tech4sky
:
<input type="text" pattern="^@[A-Za-z0-9_]{1,15}$" >
See the Pen Twitter Username Validation Example by SitePoint (@SitePoint) on CodePen.
Hex Color Code
This one matches a hexadecimal color. For example #3b5998 or #000.
<input type="text" pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" >
See the Pen Hex-Color Code Validation Example by SitePoint (@SitePoint) on CodePen.
Giving Hints
To provide the user with a description of the pattern, or an error reporting on the field if an invalid value is entered, you can use the title
attribute, like this:
<input type="text" name="ssn"
pattern="^\d{3}-\d{2}-\d{4}$"
title="The Social Security Number" />
See the Pen hbuxg by SitePoint (@SitePoint) on CodePen.
If you’re new to Regular Expressions, you can check out this document on WebPlatform.org to give you a head start. In most cases, however, you should be able to use Google to search for the regular expression you want, or even use a tool to help you.
The required
Attribute
This is a Boolean attribute used to indicate that a given input field’s value is required in order to submit the form. By adding this attribute to a form field, the browser requires the user to enter data into that field before submitting the form.
This replaces the basic form validation currently implemented with JavaScript, making things a little more usable and saving us some development time.
Example: <input type="text" name="my_name" required />
or <input type="text" name="my_name" required="required" />
for XHTML compatibility.
All the demos embedded above use the required
attribute, so you can test those by trying to submit any of the forms without entering anything in the field.
Summary
Browser support for form validation features is pretty strong, and you can easily polyfill them where necessary.
It is worth noting that relying solely on the browser (client-side) for validation can be dangerous because it can be circumvented by a malicious user or by computer bots.
Not all browsers support HTML5, and not all input sent to your script will come from the form. This means that server-side side validation should also be in place before the form data is sent to the server for processing.