logo dile-components dile-components

Custom rules

Besides the built-in rules, you can add your own rules to the forms with the DileFormValidation mixin.

Registering a rule

Register a rule to use it in every form of the application:

import { registerRule } from '@dile/validation';

registerRule('nif', {
  validate: (value) => /^[0-9]{8}[A-Z]$/.test(value),
  message: {
    en: 'Enter a valid NIF.',
    es: 'Introduce un NIF válido.',
  },
});
<dile-input name="nif" label="NIF" validations="required|nif"></dile-input>

A rule is an object with:

The context has the field name and label, the field element, the form, valueOf(name) to read other fields and isEmpty(value).

To use a rule only in one form, put it in the rules property of that form. It takes precedence over a registered rule with the same name:

form.rules = {
  even: { validate: (value) => Number(value) % 2 === 0, message: 'Enter an even number.' },
};

Inline rules

For a one-off check, use a function in the schema. It receives the value and the context, and returns true, false or a message. Like the other rules, it is skipped on empty values.

static validations = {
  end_date: [(value, context) => value >= context.valueOf('start_date') || 'The end date must be after the start date'],
};

Asynchronous rules

validate() may return a promise, for example to ask the server whether a value is available. Combine it with live validation and a debounce, so the server is not called on every key:

registerRule('availableUsername', {
  validate: async (value) => {
    const response = await fetch(`/api/usernames/${encodeURIComponent(value)}`);
    const { available } = await response.json();
    return available;
  },
  message: { en: 'This username is taken.', es: 'Este nombre de usuario ya existe.' },
});
<dile-input name="username" label="Username" validations="availableUsername" validate-on="input" validate-debounce="400"></dile-input>

Results of older asynchronous validations are discarded. See Live validation.

Demo

A local rule that simulates an asynchronous check. admin, root and dile are taken.

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

  const taken = ['admin', 'root', 'dile'];

  class CustomRuleForm extends DileFormValidation(DileForm(LitElement)) {
    constructor() {
      super();
      this.rules = {
        availableUsername: {
          validate: (value) => new Promise(resolve => setTimeout(() => resolve(!taken.includes(value.toLowerCase())), 300)),
          message: 'The username "{input}" is taken.',
        },
        even: {
          validate: (value) => Number(value) % 2 === 0,
          message: 'Enter an even number.',
        },
      };
    }

    render() {
      return html`
        <dile-input name="username" label="Username" validations="availableUsername" validate-on="input" validate-debounce="400"></dile-input>
        <dile-input name="number" label="Even number" validations="integer|even" validate-on="input"></dile-input>
      `;
    }
  }
  customElements.define('custom-rule-form', CustomRuleForm);
</script>
<custom-rule-form></custom-rule-form>