Client-Side Form Validation with HTML5

Share this article

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.

Invalid form value

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

Using the title attribute

Validating with the title attribute present

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.

The required attribute

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.

Frequently Asked Questions (FAQs) about Client-Side Form Validation in HTML5

What is the importance of client-side form validation in HTML5?

Client-side form validation in HTML5 is crucial for several reasons. Firstly, it provides immediate feedback to the user. This means that if a user makes an error while filling out a form, they are alerted instantly, without having to wait for the server to respond. This makes the user experience smoother and more efficient. Secondly, it reduces the load on the server. By catching errors on the client side, fewer invalid form requests reach the server, saving server resources. Lastly, it enhances security by preventing malicious or malformed data from being sent to the server.

How does the ‘required’ attribute work in HTML5 form validation?

The ‘required’ attribute in HTML5 form validation is used to specify that an input field must be filled out before the user can submit the form. If a user attempts to submit a form without filling out a ‘required’ field, the browser will display an error message and prevent the form from being submitted. This attribute doesn’t need a value, you simply add it to the input field like this: <input type="text" name="username" required>.

Can I customize the error messages in HTML5 form validation?

Yes, you can customize the error messages in HTML5 form validation using the ‘setCustomValidity’ method. This method allows you to set a custom validation message on an input element. The message will be displayed when the input fails validation. Here’s an example:
var input = document.getElementById('myInput');
input.setCustomValidity('Please enter a valid email address.');
In this example, if the input fails validation, the custom message ‘Please enter a valid email address.’ will be displayed.

How does the ‘pattern’ attribute work in HTML5 form validation?

The ‘pattern’ attribute in HTML5 form validation is used to specify a regular expression that the input field’s value is checked against. The regular expression defines a pattern that the input must match in order for the form to be submitted. If the input doesn’t match the pattern, the browser will display an error message and prevent the form from being submitted. Here’s an example of how to use the ‘pattern’ attribute: <input type="text" name="username" pattern="[a-zA-Z0-9]{5,}" title="Username must be alphanumeric and at least 5 characters long">.

What is the difference between client-side and server-side validation?

Client-side validation occurs in the user’s browser before the form is submitted to the server. It provides immediate feedback and enhances user experience by catching errors early. However, it can be bypassed by disabling JavaScript in the browser, so it should not be relied upon for security. Server-side validation, on the other hand, occurs on the server after the form has been submitted. It is more secure because it cannot be bypassed, but it can be slower because it requires a round trip to the server.

How can I use JavaScript to enhance HTML5 form validation?

JavaScript can be used to enhance HTML5 form validation in several ways. For example, you can use JavaScript to perform more complex validation checks that are not possible with HTML5 alone, such as checking if a username is already taken. You can also use JavaScript to customize the appearance and behavior of validation error messages, or to perform validation checks in real-time as the user fills out the form.

Can I use HTML5 form validation for all types of input fields?

HTML5 form validation can be used for many types of input fields, including text fields, email fields, number fields, and more. However, it may not be suitable for all types of input. For example, HTML5 form validation does not support file inputs, so you would need to use JavaScript or server-side validation for these.

How does the ‘min’ and ‘max’ attributes work in HTML5 form validation?

The ‘min’ and ‘max’ attributes in HTML5 form validation are used to specify the minimum and maximum values for an input field. These attributes are particularly useful for number and date input types. If a user enters a value that is less than the ‘min’ value or greater than the ‘max’ value, the browser will display an error message and prevent the form from being submitted. Here’s an example of how to use these attributes: <input type="number" name="age" min="18" max="99">.

What is the ‘novalidate’ attribute in HTML5 form validation?

The ‘novalidate’ attribute in HTML5 form validation is used to disable validation for a form. When this attribute is present, the browser will not perform any validation checks when the form is submitted. This can be useful in certain situations, such as when you want to perform all validation on the server side. However, it should be used with caution, as it removes the user-friendly feedback provided by client-side validation.

Can I use HTML5 form validation in all browsers?

HTML5 form validation is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. However, it is not supported in Internet Explorer 9 and earlier versions. If you need to support these older browsers, you will need to use JavaScript or server-side validation as a fallback.

Collins AgbonghamaCollins Agbonghama
View Author

Collins is a web developer and freelance writer. Creator of the popular ProfilePress and MailOptin WordPress plugins. When not wrangling with code, you can find him writing at his personal blog or on Twitter.

form validationHTML5 Formshtml5 inputs
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week