logo dile-components dile-components

Live validation

Forms with the DileFormValidation mixin validate the fields while the user fills them, not only when validate() is called.

Validation modes

The validateOn property decides when the fields are validated while the user fills the form. A field can override it with the validate-on attribute.

Mode Behavior
eager (default) Nothing is validated until the user leaves the field or the form is validated. From then on, a field with an error is validated again on every change, so the message disappears as soon as it is fixed.
blur Each field is validated when the user leaves it.
input Each field is validated on every change.
submit Only validate() validates.
<dile-input name="slug" label="Slug" validations="pattern:[a-z0-9-]+" validate-on="input"></dile-input>

For rules that are slow or check the server, set validateDebounce (milliseconds) on the form, or the validate-debounce attribute on a field. A change then waits that time without new changes before validating. Leaving the field validates at once.

<dile-input name="username" label="Username" validations="availableUsername" validate-on="input" validate-debounce="400"></dile-input>

Only fields that the user has focused are validated live, so setData() or the initial values never show errors. Results of older asynchronous validations are discarded.

A live validation waits for the pending render of the form, so it uses the attributes the form sets after a change, like ?required=${this.isCompany}. When a render changes whether a field with an error is required, disabled or (with skip-hidden) hidden, the form validates it again: the error of a field that is no longer required disappears. When the error is cleared, the help text the field had in message comes back (see Help texts).

Note: fields with hideErrorOnInput work with live validation. In eager and input modes the form validates the field again on every change instead of letting the field hide its error: the message stays until the new value is valid, also while a validateDebounce or an asynchronous rule is pending, so it does not flicker. This applies to the errors of the server too (showErrors()): they disappear when the new value passes the client rules. Leaving a field without changing its value keeps the error it shows: the client rules may not know an error of the server (unique, exists...) or one shown with showError(), and nothing changed. If the value changes and goes back to the one that had the error, the error stays too. In blur and submit modes, hideErrorOnInput keeps hiding the error while typing, and it comes back when the field is validated again.

Fields that depend on other fields

Rules that read another field, such as same, different, requiredIf or an inline rule that calls context.valueOf(), are validated again when that other field changes. The form records the fields that each rule reads with valueOf(), so these dependencies need no configuration:

static validations = {
  password_confirmation: 'same:password',
  exemption_reason: [(value, context) => Number(context.valueOf('vat')) === 0 || 'An exemption reason needs a 0% VAT'],
};

Changing the password validates the confirmation again, and setting the VAT to 0 clears the error of the exemption reason. A dependent field is only validated again when it shows an error or the user has already focused it, so untouched fields never show errors. When the value changes from code (setData(), or a handler that fills a field), only the dependent fields that show an error are validated again, so a stale error disappears without showing new ones. Its own validate-on (except submit, which is never validated live) and validate-debounce apply.

When a rule depends on a field without reading it with valueOf() (for example, it reads a property of the form), declare the dependency with dependsOn in the schema or with the validate-depends-on attribute, a comma separated list of names:

static validations = {
  end_date: { rules: ['required', 'availableDate'], dependsOn: ['start_date', 'room'] },
};
<dile-input name="zip" label="ZIP" validations="zipCode" validate-depends-on="country"></dile-input>

Demo

Each field uses a different mode. Type and leave the fields to compare them.

<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';

  class LiveModesForm extends DileFormValidation(DileForm(LitElement)) {
    static validations = {
      eager: 'email',
      blur: 'email',
      input: 'email',
      submit: 'email',
      password: 'minLength:8',
      password_confirmation: 'same:password',
    };

    render() {
      return html`
        <dile-input name="eager" label="Email (eager, the default)"></dile-input>
        <dile-input name="blur" label="Email (blur)" validate-on="blur"></dile-input>
        <dile-input name="input" label="Email (input)" validate-on="input"></dile-input>
        <dile-input name="submit" label="Email (submit)" validate-on="submit"></dile-input>
        <dile-input name="password" label="Password" type="password"></dile-input>
        <dile-input name="password_confirmation" label="Repeat password (depends on Password)" type="password"></dile-input>
        <dile-button @click=${() => this.validate()}>Validate</dile-button>
      `;
    }
  }
  customElements.define('live-modes-form', LiveModesForm);
</script>
<live-modes-form></live-modes-form>