Form validation helps us to ensure that users fill out forms in the correct format, making sure that submitted data will work successfully with our applications. This article leads you through basic concepts and examples about form validation. For more information beyond this tutorial, see the Constraint validation guide.

To understand what form validation is, why it's important, and to apply various techniques to implement it.

What is form validation?

Go to any popular site with a registration form, and you will notice that they give you feedback when you don't enter your data in the format they are expecting. You'll get messages such as:

"This field is required" (you can't leave this field blank)

"Please enter your phone number in the format xxx-xxxx" (it enforces three numbers followed by a dash, followed by four numbers)

"Please enter a valid e-mail address" (if your entry is not in the format of "somebody@example.com")

"Your password needs to be between 8 and 30 characters long, and contain one uppercase letter, one symbol, and a number"

This is called form validation — when you enter data, the web application checks it to see that the data is correct. If correct, the application allows the data to be submitted to the server and (usually) saved in a database; if not, it gives you an error message explaining what corrections need to be made. Form validation can be implemented in a number of different ways.

We want to make filling out web forms as easy as possible. So why do we insist on validating our forms? There are three main reasons:

We want to get the right data, in the right format — our applications won't work properly if our user's data is stored in the incorrect format, or if they don't enter the correct information, or omit information altogether.

We want to protect our users' accounts — by forcing our users to enter secure passwords, it makes it easier to protect their account information.

We want to protect ourselves — there are many ways that malicious users can misuse unprotected forms to damage the application they are part of (see Website security).

Warning: Never trust data passed to your server from the client. Even if your form is validating correctly and preventing malformed input, a malicious user can still alter the network request.

Different types of form validation

There are two different types of form validation which you'll encounter on the web:

Client-side validation is validation that occurs in the browser before the data has been submitted to the server. This is more user-friendly than server-side validation as it gives an instant response. This can be further subdivided:

JavaScript validation is coded using JavaScript. It is completely customizable.

Built-in form validation using HTML5 form validation features. This generally does not require JavaScript. Built-in form validation has better performance, but it is not as customizable as JavaScript.

Server-side validation is validation which occurs on the server after the data has been submitted. Server-side code is used to validate the data before it is saved into the database. If the data fails authentication, a response is sent back to the client to tell the user what corrections to make. Server-side validation is not as user-friendly as client-side validation, as it does not provide errors until the entire form has been submitted. However, server-side validation is your application's last line of defence against incorrect or even malicious data. All popular server-side frameworks have features for validating and sanitizing data (making it safe).

In the real world, developers tend to use a combination of client-side and server-side validation.

Using built-in form validation

One of the features of HTML5 is the ability to validate most user data without relying on scripts. This is done by using validation attributes on form elements, which allow you to specify rules for a form input like whether a value needs to be filled in, the minimum and maximum length of the data, whether it needs to be a number, an email address, or something else, and a pattern that it must match. If the entered data follows all the specified rules, it is considered valid; if not, it is considered invalid.

When an element is valid:

The element matches the :valid CSS pseudo-class; this will let you apply a specific style to valid elements.

If the user tries to send the data, the browser will submit the form, provided there is nothing else stopping it from doing so (e.g., JavaScript).

When an element is invalid:

The element matches the :invalid CSS pseudo-class; this will let you apply a specific style to invalid elements.

If the user tries to send the data, the browser will block the form and display an error message.

Validation constraints on input elements — starting simple

In this section, we'll look at some of the different HTML5 features that can be used to validate <input> elements.

Let's start with a simple example — an input that allows you to choose your favorite fruit out of a choice of banana or cherry. This involves a simple text <input> with a matching label, and a submit <button>. You can find the source code on GitHub as fruit-start.html, and a live example below:

To begin with, make a copy of fruit-start.html in a new directory on your hard drive.

The required attribute

The simplest HTML5 validation feature to use is the required attribute — if you want to make an input mandatory, you can mark the element using this attribute. When this attribute is set, the form won't submit (and will display an error message) when the input is empty (the input will also be considered invalid).

This causes the input to have a bright red dashed border when it is invalid, and a more subtle black border when valid. Try out the new behaviour in the example below:

Validating against a regular expression

Another very common validation feature is the pattern attribute, which expects a Regular Expression as its value. A regular expression (regex) is a pattern that can be used to match character combinations in text strings, so they are ideal for form validation (as well as a variety of other uses in JavaScript). Regexs are quite complex and we do not intend to teach you them exhaustively in this article.

Below are some examples to give you a basic idea of how they work:

a — matches one character that is a (not b, not aa, etc.)

abc — matches a, followed by b, followed by c.

a* — matches the character a, zero or more times (+ matches a character one or more times).

[^a] — matches one character that is not a.

a|b — matches one character that is a or b.

[abc] — matches one character that is a, b, or c.

[^abc] — matches one character that is not a, b, or c.

[a-z] — matches any character in the range a–z, lower case only (you can use [A-Za-z] for lower and upper case, and [A-Z] for upper case only).

a.c — matches a, followed by any character, followed by c.

a{5} — matches a, 5 times.

a{5,7} — matches a, 5 to 7 times, but no less or more.

You can use numbers and other characters in these expressions too, such as:

[ -] — matches a space or a dash.

[0-9] — matches any digit in the range 0 to 9.

You can combine these in pretty much any way you want, specifying different parts one after the other:

[Ll].*k — A single character that is an upper or lowercase L, followed by zero or more characters of any type, followed by a single lowercase k.

[A-Z][A-Za-z' -]+ — A single uppercase character followed by one or more characters that are an upper or lower case letter, a dash, an apostrophe, or space. This could be used to validate the city/town names of English-speaking countries, which need to start with a capital letter but don't contain any other characters. Examples from the UK include Manchester, Ashton-under-lyne, and Bishop's Stortford.

[0-9]{3}[ -][0-9]{3}[ -][0-9]{4} — A simple match for a US domestic phone number — three digits, followed by a space or a dash, followed by three digits, followed by a space or a dash, followed by four digits. You might have to make this more complex, as some people write their area code in parentheses, but it works for a simple demonstration.

In this example, the <input> element accepts one of two possible values: the string "banana" or the string "cherry".

At this point, try changing the value inside the pattern attribute to equal some of the examples you saw earlier, and look at how that affects the values you can enter to make the input value valid. Try writing some of your own, and see how you get on! Try to make them fruit-related where possible, so your examples make sense!

Note: Some <input> element types do not need a pattern attribute to be validated. Specifying the email type for example validates the inputted value against a regular expression matching a well-formed email address (or a comma-separated list of email addresses if it has the multiple attribute). As a further example, fields with the url type automatically require a properly-formed URL.

Constraining the length of your entries

All text fields created by <input> or <textarea> can be constrained in size using the minlength and maxlength attributes. A field is invalid if its value is shorter than the minlength value or longer than the maxlength value. Browsers often don't let the user type a longer value than expected into text fields anyway, but it is useful to have this fine-grained control available.

For number fields (i.e. <input type="number">), the min and max attributes also provide a validation constraint. If the field's value is lower than the min attribute or higher than the max attribute, the field will be invalid.

Here you'll see that we've given the text field a minlength and maxlength of 6 — the same length as banana and cherry. Entering less characters will show as invalid, and entering more is not possible in most browsers.

We've also given the number field a min of 1 and a max of 10 — entered numbers outside this range will show as invalid, and you won't be able to use the increment/decrement arrows to move the value outside this range.

Note: <input type="number"> (and other types, like range) can also take a step attribute, which specifies what increment the value will go up or down by when the input controls are used (like the up and down number buttons).

Full example

Here is a full example to show off usage of HTML's built-in validation features:

Constraint validation API properties

Property

Description

validationMessage

A localized message describing the validation constraints that the control does not satisfy (if any), or the empty string if the control is not a candidate for constraint validation (willValidate is false), or the element's value satisfies its constraints.

validity

A ValidityState object describing the validity state of the element. See that article for details of possible validity states.

willValidate

Returns true if the element will be validated when the form is submitted; false otherwise.

Constraint validation API methods

Method

Description

checkValidity()

Returns true if the element's value has no validity problems; false otherwise. If the element is invalid, this method also causes an invalid event at the element.

Returns true if the element or its child controls satisfy validation constraints. When false is returned, cancelable invalid events are fired for each invalid element and validation problems are reported to the user.

setCustomValidity(message)

Adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is displayed. This lets you use JavaScript code to establish a validation failure other than those offered by the standard constraint validation API. The message is shown to the user when reporting the problem.

If the argument is the empty string, the custom error is cleared.

For legacy browsers, it's possible to use a polyfill such as Hyperform to compensate for the lack of support for the constraint validation API. Since you're already using JavaScript, using a polyfill isn't an added burden to your Web site or Web application's design or implementation.

Example using the constraint validation API

Let's see how to use this API to build custom error messages. First, the HTML:

This simple form uses the novalidate attribute to turn off the browser's automatic validation; this lets our script take control over validation. However, this doesn't disable support for the constraint validation API nor the application of the CSS pseudo-class :valid, :invalid, :in-range and :out-of-range classes. That means that even though the browser doesn't automatically check the validity of the form before sending its data, you can still do it yourself and style the form accordingly.

The aria-live attribute makes sure that our custom error message will be presented to everyone, including those using assistive technologies such as screen readers.

CSS

This CSS styles our form and the error output to look more attractive.

JavaScript

The following JavaScript code handles the custom error validation.

// There are many ways to pick a DOM node; here we get the form itself and the email
// input box, as well as the span element into which we will place the error message.
var form = document.getElementsByTagName('form')[0];
var email = document.getElementById('mail');
var error = document.querySelector('.error');
email.addEventListener("input", function (event) {
// Each time the user types something, we check if the
// email field is valid.
if (email.validity.valid) {
// In case there is an error message visible, if the field
// is valid, we remove the error message.
error.innerHTML = ""; // Reset the content of the message
error.className = "error"; // Reset the visual state of the message
}
}, false);
form.addEventListener("submit", function (event) {
// Each time the user tries to send the data, we check
// if the email field is valid.
if (!email.validity.valid) {
// If the field is not valid, we display a custom
// error message.
error.innerHTML = "I expect an e-mail, darling!";
error.className = "error active";
// And we prevent the form from being sent by canceling the event
event.preventDefault();
}
}, false);

Here is the live result:

The constraint validation API gives you a powerful tool to handle form validation, letting you have enormous control over the user interface above and beyond what you can do just with HTML and CSS alone.

Validating forms without a built-in API

Sometimes, such as with legacy browsers or custom widgets, you will not be able to (or will not want to) use the constraint validation API. In that case, you're still able to use JavaScript to validate your form. Validating a form is more a question of user interface than real data validation.

To validate a form, you have to ask yourself a few questions:

What kind of validation should I perform?

You need to determine how to validate your data: string operations, type conversion, regular expressions, etc. It's up to you. Just remember that form data is always text and is always provided to your script as strings.

What should I do if the form does not validate?

This is clearly a UI matter. You have to decide how the form will behave: Does the form send the data anyway? Should you highlight the fields which are in error? Should you display error messages?

How can I help the user to correct invalid data?

In order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs. You should offer up-front suggestions so they know what's expected, as well as clear error messages. If you want to dig into form validation UI requirements, there are some useful articles you should read:

As you can see, it's not that hard to build a validation system on your own. The difficult part is to make it generic enough to use it both cross-platform and on any form you might create. There are many libraries available to perform form validation; you shouldn't hesitate to use them. Here are a few examples:

Remote validation

In some cases, it can be useful to perform some remote validation. This kind of validation is necessary when the data entered by the user is tied to additional data stored on the server side of your application. One use case for this is registration forms, where you ask for a username. To avoid duplication, it's smarter to perform an AJAX request to check the availability of the username rather than asking the user to send the data, then send back the form with an error.

Performing such a validation requires taking a few precautions:

It requires exposing an API and some data publicly; be sure it is not sensitive data.

Network lag requires performing asynchronous validation. This requires some UI work in order to be sure that the user will not be blocked if the validation is not performed properly.

Conclusion

Form validation does not require complex JavaScript, but it does require thinking carefully about the user. Always remember to help your user to correct the data they provide. To that end, be sure to: