Validation
Show the browser's own validation as an error under each field, with the right ARIA, instead of the browser bubble.
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.
<form class="stack" data-validate>
<div class="field">
<label for="vd-email">Email</label>
<input id="vd-email" name="email" type="email" required
data-message="Enter an email like name@example.com"
aria-describedby="vd-email-hint" />
<small id="vd-email-hint">We never share it.</small>
</div>
<div class="field">
<label for="vd-zip">ZIP code</label>
<input id="vd-zip" name="zip" inputmode="numeric" pattern="[0-9]{5}" required
data-message="Enter a 5 digit ZIP code" />
</div>
<div class="field">
<input id="vd-terms" name="terms" type="checkbox" required
data-message="Accept the terms to continue" />
<label for="vd-terms">I accept the terms</label>
</div>
<button type="submit" class="btn" data-variant="primary">Send</button>
</form>
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
smallwithdata-errorinside the.field(it makes one if there is none) and adds its id to the field'saria-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. |