Getting started with validation
Dile Components validate forms in the browser before the data reaches your server, and show the errors of the client and of the server in the same way. Validation is built in layers, so you only load what you use:
| Layer | Package | What it checks |
|---|---|---|
| Required fields | @dile/ui (DileForm) |
Fields with the required attribute must have a value. |
| Fields' own errors | @dile/ui |
Each field reports the errors it can detect by itself: an impossible date in dile-datepicker, an incomplete dile-input-mask, an invalid dile-input-phone, a text that is not a number in dile-input-money... |
| Rules | @dile/validation (DileFormValidation) |
Rules like email, minLength, between, same, pattern, file and image rules, IBAN, Spanish tax IDs, your own rules... and live validation while the user types. |
The first two layers are always there: any form with the DileForm mixin, and any Dile field inside a plain HTML <form> (native forms), already blocks empty required fields and impossible values. Add @dile/validation when you need rules.
Installation
npm i @dile/ui @dile/validation
Your first validated form
Create a form with the DileForm mixin, apply DileFormValidation on top and declare the rules of each field:
import { LitElement, html } from 'lit';
import { DileForm } from '@dile/ui/mixins/form';
import { DileFormValidation } from '@dile/validation';
import '@dile/ui/components/input/input.js';
class ContactForm extends DileFormValidation(DileForm(LitElement)) {
static validations = {
email: 'email|maxLength:120',
phone: 'pattern:[0-9]{9}',
};
render() {
return html`
<dile-input name="name" label="Name" required></dile-input>
<dile-input name="email" label="Email" required></dile-input>
<dile-input name="phone" label="Phone"></dile-input>
`;
}
}
customElements.define('contact-form', ContactForm);
Then validate the form before using its data:
const { valid, errors } = await form.validate();
if (valid) {
send(form.getData());
}
validate() shows the first error of each field, moves the focus to the first invalid field (opening the collapsed containers that hide it) and dispatches dile-form-validated.
Rules can also be written in the field, with the validations attribute:
<dile-input name="code" label="Code" validations="required|pattern:[A-Z]{3}[0-9]{2}"></dile-input>
See Declaring rules for every way to declare them.
Order of the checks
For each field, the first error found wins:
- Required: the
requiredattribute or property. - The field's own validation: its
getValidationError()method. - Rules: the rules of
@dile/validation.
Disabled and readonly fields are not validated, as in native forms. Hidden fields are validated unless the form has skip-hidden (see Hidden fields).
Client and server errors look the same
The errors of validate() have the shape { fieldName: message }, with items.0, items.1... for the elements of array fields (name="items[]"). It is the same shape that showErrors() receives with the errors of the server, so both are shown in the fields in the same way:
// errors from Laravel or any other backend
form.showErrors({ email: ['The email has already been taken.'] });
form.focusFirstError();
The client validation is a help for the user, not a security barrier: the server must always validate the data. The CRUD components already show the server errors in the fields (see Validation in the CRUD).
Where to go next
- Rules reference: every built-in rule.
- Live validation: validate while the user fills the form.
- Messages and languages: English and Spanish messages, and your own texts.
- Custom rules: your own rules, also asynchronous ones that ask the server.
Demo
<script type="module">
import { LitElement, html } from 'lit';
import { DileForm } from '@dile/ui/mixins/form';
import { DileFormValidation } from '@dile/validation';
import '@dile/ui/components/input/input.js';
import '@dile/ui/components/button/button.js';
import '@dile/utils/components/datepicker/datepicker.js';
class GettingStartedForm extends DileFormValidation(DileForm(LitElement)) {
static validations = {
email: 'email|maxLength:120',
phone: 'pattern:[0-9]{9}',
};
static properties = { result: { type: String } };
render() {
return html`
<dile-input name="name" label="Name" required></dile-input>
<dile-input name="email" label="Email" required></dile-input>
<dile-input name="phone" label="Phone (nine digits)"></dile-input>
<dile-datepicker name="birthday" label="Birthday (try an impossible date)"></dile-datepicker>
<p><dile-button @click=${this.send}>Send</dile-button></p>
<p>${this.result}</p>
`;
}
async send() {
const { valid } = await this.validate();
this.result = valid ? `Valid data: ${JSON.stringify(this.getData())}` : 'Please review the form';
}
}
customElements.define('getting-started-form', GettingStartedForm);
</script>
<getting-started-form></getting-started-form>
dile-components