logo dile-components dile-components

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

Fields report, the form shows. isEmpty() and getValidationError() must not change errored or message: 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.