Validation

A form that checks itself

Add data-validate to a form. Write the rules in HTML as usual: required, type="email", pattern, minlength. Leave a field and it is checked; once it shows an error it is checked again as you type. Submitting checks every field and moves focus to the first one that fails.

We never share it.

What it does to a field

  • Sets aria-invalid="true" on the field, so its border turns danger, and removes it when the field is valid.
  • Puts the message in a small with data-error inside the .field (it makes one if there is none) and adds its id to the field's aria-describedby, next to any hint you wrote.
  • Gives the message role="alert" while it shows, so a screen reader reads it as soon as it appears.
  • Turns off the browser bubble with novalidate, and clears every error when the form is reset.

Without the script nothing is lost: the browser validates on submit as usual, and a field the user has left invalid gets the danger border from :user-invalid.

JavaScript

Fields added later are picked up. To check from your own code, for example after a server reply, use the API below.

Call Description
tsunami.validate.check(el) Checks a form or one field, shows the errors and returns true when it is valid.
tsunami.validate.clear(el) Removes the errors of a form or one field.

Attributes

Attribute On Description
data-validate form Turns on the checks above.
data-message field The error text. Without it the browser's own text is used.
data-error small Where the message goes. Optional: it is made for you.