Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 56 ยท Forms

Form Validation

Validate forms with jQuery: handle submit, check required fields and patterns, show accessible inline errors with aria-invalid and aria-describedby, and use browser validation.

Validation answers one question before data leaves the page: is what the user typed usable? Good validation does three things. It catches mistakes early, it explains each problem next to the field where it happened, and it never locks out people who use screen readers or keyboards. It is also only a convenience. Anyone can bypass browser code, so the server must always validate again.

In this lesson you will write validation by hand with jQuery. You will intercept the submit event, check required fields and patterns, show errors that assistive technology can announce, and combine your code with the browser's built-in constraint validation so you write less. You should be comfortable with events and form values.

A validation round trip

Submit Intercept the form's submit event.
Check Test every field against its rules.
Explain Show one message beside each bad field.
Focus Move the cursor to the first problem.
1 / 2

Intercept the submit event

Validate on the form's submit event, not on the button's click. The submit event also fires when the user presses Enter inside a field, which a click handler would miss. Call event.preventDefault() to stop the browser from sending the form when something is wrong (and, in the demos here, always, because nothing may be posted).

JavaScript
$("#signup").on("submit", function (event) {
  var valid = validate($(this));
  if (!valid) {
    event.preventDefault();
  }
});

Required fields and patterns

The checks themselves are ordinary JavaScript. A field is required when its trimmed value is empty. A pattern check tests the value against a regular expression, for instance a simple email shape (/^[^@\s]+@[^@\s]+\.[^@\s]+$/). Keep the rules in one place, an object keyed by field name, so adding a rule means adding a line rather than another if branch.

Avoid over-clever email regexes. The only reliable way to know an address works is to send a message to it, so a loose check that catches typos is enough.

Showing errors the right way

An error message has to be tied to its field, otherwise a screen reader user hears the field name but never the problem. Two ARIA attributes do the job:

  • aria-invalid="true" on the field tells assistive technology its value is wrong.
  • aria-describedby="email-error" points to the message element, so the message is read together with the field.

Create the message element once per field, give it the id, and fill it with .text() when needed. For the messages to be announced when they appear, a common approach is an error summary with role="alert" at the top, plus per-field messages. Finally, move focus to the first invalid field so keyboard users land exactly where the work is.

JavaScript
function showError($field, message) {
  var id = $field.attr("id") + "-error";
  var $error = $("#" + id);
  if (!$error.length) {
    $error = $("<p>", { id: id, "class": "error" }).insertAfter($field);
  }
  $error.text(message);
  $field.attr({ "aria-invalid": "true", "aria-describedby": id });
}

function clearError($field) {
  $("#" + $field.attr("id") + "-error").remove();
  $field.removeAttr("aria-invalid aria-describedby");
}

Notice that aria-invalid and aria-describedby are attributes, so .attr() is the right tool here, not .prop() (see attributes and properties).

Inline validation with accessible errors

Notice two choices. The blur handler is delegated, because blur does not bubble in the DOM; jQuery maps delegated blur to focusout for you (see event delegation). And the blur check skips empty fields, so a user who tabs through the form is not scolded for fields they have not reached yet.

Combine with browser validation

HTML already ships a validation engine. Attributes such as required, type="email", minlength, pattern and min / max make the browser check the value, and the Constraint Validation API exposes the result to JavaScript:

  • field.validity is an object with flags such as valueMissing, typeMismatch, patternMismatch and tooShort.
  • field.validationMessage is the browser's own message, in the user's language.
  • field.checkValidity() returns true or false.
  • field.setCustomValidity("text") adds your own error; an empty string clears it.

You do not have to choose between this and your own styling. Put novalidate on the form so the browser does not show its own popups, then read validity to decide which message to display. That way the rules live in your HTML where they belong, and jQuery only handles presentation.

Using the Constraint Validation API from jQuery

A few rules of thumb

  • Validate on the server too. Client checks improve the experience; only server checks protect your data.
  • Say what is wrong and how to fix it. "Invalid input" helps nobody; "Use exactly four digits" does.
  • Do not show errors before the user has had a chance. Validate on submit and on blur, not on the first keystroke.
  • Keep the user's input. Never clear a field because it failed validation.
  • Never post by accident. When testing, call event.preventDefault() unconditionally, as the demos here do.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is it better to validate in the form's submit event than in the submit button's click event?

    Pressing Enter inside a text field submits the form without clicking the button, so only a submit handler covers every path.
  2. 2. What is the purpose of aria-describedby on an invalid field?

    aria-describedby references the id of the message element, so a screen reader announces the message together with the field.
  3. 3. Which call stops the form from being sent when validation fails?

    preventDefault() cancels the browser's default action, which for a submit event is sending the form.
  4. 4. What does the novalidate attribute on a form do?

    novalidate suppresses the browser's built-in UI at submit time. The validity API still works, so you can read the results and render your own messages.
  5. 5. Client-side validation is enough to protect your database from bad data.

    Anyone can disable JavaScript or send requests directly. Treat client validation as a convenience and always validate on the server.

Summary

  • Validate in the submit event and call event.preventDefault() when something is wrong.
  • Keep rules together in one object; check required values after trimming and patterns with regular expressions.
  • Show a message beside each bad field, link it with aria-describedby, mark the field with aria-invalid, and move focus to the first problem.
  • Use the Constraint Validation API (validity, checkValidity(), setCustomValidity()) together with novalidate to reuse rules declared in HTML.
  • Validate again on the server; client-side checks are only a convenience.

Next, learn the helper functions that live directly on the $ object in Utility Functions.