Validation in your own fields
Validation is not limited to the Dile fields. Any element with a name inside a DileForm takes part in it, so your own fields get the required check, the rules of @dile/validation, live validation and the error display for free.
Field validation contract
- required property or attribute: marks the field as required.
- isEmpty() (optional): returns
truewhen the field has no value. Without it,undefined,null, empty or whitespace-only strings and empty arrays are empty, andfalseis a value. - getValidationError({ messages }) (optional): returns the error message of the field, or
''when it is valid. Use it for the errors that only the field can detect, like an impossible date.messageshas the messages of the form for this field, by reason: use them before your default texts. - focus() (optional): used to focus the first invalid field. Without it, the form focuses the first focusable element inside the field.
- errored and message properties: the form uses them to show the errors. The DileFieldMessage mixin provides them, with a message template.
Fields report, the form shows.
isEmpty()andgetValidationError()must not changeerroredormessage: they only report. The form decides when to show the errors.
import { LitElement, html } from 'lit';
import { DileEmmitChange, DileFieldMessage } from '@dile/ui/mixins/form';
class MyRgbField extends DileFieldMessage(DileEmmitChange(LitElement)) {
static properties = {
name: { type: String },
value: { type: String },
required: { type: Boolean, reflect: true },
};
getValidationError() {
if (this.value && !/^#[0-9a-f]{6}$/i.test(this.value)) {
return 'Write a color like #33aaff.';
}
return '';
}
render() {
return html`
<input .value=${this.value ?? ''} @input=${(e) => { this.value = e.target.value; this.emmitChange(); }}>
${this.messageTemplate}
`;
}
}
The full details are in DileForm: field validation contract.
Wrapping a Dile field
When your field only wraps a Dile field, like a my-vat-select that renders a dile-select with the VAT options, use the DileFieldWrapper mixin and the fieldProps() directive. They forward required, errored, message and the rest of the contract to the inner field, and delegate isEmpty(), getValidationError() and focus() on it. See Wrapping a field.
Native HTML forms
Apply the DileNativeValidity mixin to a form-associated field to make the same contract work in a plain <form>, with checkValidity(), reportValidity(), :invalid and the user-invalid attribute. The Dile fields already apply it.
Fields inside collapsed containers
When a field with an error is inside a closed container, the form dispatches the dile-reveal event so the container can open. Your own containers can take part too. See Fields inside collapsed containers.
dile-components