logo dile-components dile-components

DileFormValidation

Mixin that adds validation rules and live validation to a DileForm element. It lives in its own package, @dile/validation, so applications only load it in the forms that use it.

Without this package, DileForm already checks required fields and the fields' own errors (an impossible date, an incomplete mask...). See DileForm validation. This mixin adds rules like email, minLength or pattern, custom rules and validation while the user fills the form.

Installation

npm i @dile/validation

Usage

Apply the mixin on top of DileForm 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 SignupForm extends DileFormValidation(DileForm(LitElement)) {
  static validations = {
    email: 'required|email|maxLength:120',
    age: ['integer', ['between', 18, 120]],
    password_confirmation: 'same:password',
  };

  render() {
    return html`
      <dile-input name="email" label="Email"></dile-input>
      <dile-input name="age" label="Age"></dile-input>
      <dile-input name="password" label="Password" type="password" required validations="minLength:8"></dile-input>
      <dile-input name="password_confirmation" label="Repeat password" type="password"></dile-input>
    `;
  }
}
customElements.define('signup-form', SignupForm);

Then validate the form before using its data:

const { valid, errors } = await form.validate();

validate() is the method of DileForm: it checks, for each field, the required attribute, the field's own validation and then the rules of this mixin. The first error of each field is shown in the field.

Declaring rules

The rules of a field come from the first of these sources that has them:

  1. A schema set with setValidationSchema(schema), for example from the CRUD configuration.
  2. The static validations property of the form class.
  3. The validations attribute of the field.

The attribute uses a string with the rules separated by |, and the parameters after :, separated by commas:

<dile-input name="code" label="Code" validations="required|pattern:[A-Z]{3}[0-9]{2}"></dile-input>

The schema accepts the same strings, or arrays where each item is:

Use the array syntax for patterns that contain |, since in strings | separates rules.

A schema entry can also be an object { rules, dependsOn }, where rules is any of the formats above and dependsOn lists the fields it depends on (see Fields that depend on other fields).

Array fields (name="items[]") use the rules of items (or items.*) for every element.

Note: required can be used as an attribute or as a rule. The attribute is preferable, because it also shows the required indicator and sets aria-required.

Rules

Rules other than required, requiredIf and accepted are skipped when the value is empty: use required to make a field mandatory. Numeric rules convert numeric strings, like the values of dile-input-integer, dile-input-number, dile-input-money or dile-input-percentage, which keep value normalized with . as decimal separator while typing, so the rules work before the blur.

Rule Example Description
required required The field must have a value. Same criterion as the required attribute: whitespace-only text and empty arrays are empty, false is a value.
requiredIf requiredIf:type,company Required when another field has one of the values. Without values, when the other field is not empty.
accepted accepted The value must be true, "true", 1, "1", "yes" or "on".
email email A valid email address.
url url A valid http or https URL.
numeric numeric A number (decimal point, not comma).
integer integer A whole number.
decimal decimal:0,2 A number with a decimal point and between min and max decimal places, like Laravel's decimal. With one parameter (decimal:2), exactly that many. 12, 12.5, 12. and .5 pass decimal:0,2; 12.345 and 12,5 do not.
min min:18 A number equal to or greater than the parameter.
max max:99 A number equal to or less than the parameter.
between between:1,10 A number between both parameters, included.
minLength minLength:3 At least this number of characters, or items in arrays.
maxLength maxLength:120 No more than this number of characters, or items in arrays.
pattern pattern:[A-Z]{3} A regular expression. As in the HTML pattern attribute, a string must match the whole value. A RegExp (schema only) is used as it is.
in in:draft,published One of the values.
notIn notIn:admin,root None of the values.
same same:password The same value as another field.
different different:old_password A different value from another field.
file file The value must be a file, or a list of files.
fileType fileType:image/*,.pdf Allowed file types, with the syntax of the HTML accept attribute.
maxFileSize maxFileSize:2MB Maximum size of each file.
minFileSize minFileSize:10KB Minimum size of each file.
image image Each file must be an image the browser can read.
minImageWidth minImageWidth:800 Minimum width of each image, in pixels.
maxImageWidth maxImageWidth:4000 Maximum width of each image, in pixels.
minImageHeight minImageHeight:600 Minimum height of each image, in pixels.
maxImageHeight maxImageHeight:3000 Maximum height of each image, in pixels.

File rules

The file rules validate fields whose value is a File or a list of files, like dile-drop-file, also with multiple: every file must pass.

<dile-drop-file name="photo" label="Photo" validations="image|maxFileSize:2MB|minImageWidth:800|maxImageWidth:4000"></dile-drop-file>
<dile-drop-file name="attachments" label="Attachments" multiple validations="fileType:.pdf,image/*|maxFileSize:5MB|maxLength:3"></dile-drop-file>

The helpers parseFileSize(size), formatFileSize(bytes) and readImageDimensions(file) are exported by the package.

Messages

The messages are available in English and Spanish. The language is the one of the form: its language property, the closest lang attribute, the default language set with setDefaultLanguage(), the lang attribute of the document or English. See Language of the messages.

Customize them with the validationMessages property of the form, by rule or by field and rule. Placeholders like {min}, {max} or {other} are replaced with the rule parameters:

form.validationMessages = {
  required: 'Please fill in this field',
  minLength: 'At least {min} characters, please',
  'email.email': 'This email address does not look right',
};

To translate or change the messages of the whole application, or to add another language, use registerMessages():

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

registerMessages('fr', {
  required: 'Ce champ est obligatoire.',
  email: 'Saisissez une adresse e-mail valide.',
});

The message keys are the rule names, plus minLength.array and maxLength.array for arrays, decimal.exact for decimal when both parameters are equal (decimal:2) and invalid for the generic message.

The message of an error is the first one found in this order, both for the rules and for the required attribute of the fields:

  1. The message of the rule item in the schema, if any.
  2. The messages of setValidationSchema() and validationMessages (the former win on the same key), by field and rule: email.required. For array fields (items[], keys items.0, items.1...) also items.0.required, then items.required and items.*.required.
  3. The same messages, by rule: required.
  4. The messages of registerMessages() in the form language, then the default ones in English.

{label} is replaced with the label of the field, or its name.

Custom rules

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'],
};

Live validation

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.

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. 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. 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>

Validation in the CRUD

The @dile/crud components validate their forms before sending them: dile-ajax-form (and so dile-crud-insert, dile-crud-update and their modal versions), the action forms of dile-crud-actions and the steps of dile-steps-form. They use validate() of the form, so a form with this mixin works there without extra code.

The rules can also be declared in the resource configuration, with different rules for insert, update and each action. The CRUD hands them to the form with setValidationSchema().

Validating data without a form

The Validator class validates plain objects, for example in tests or in components that are not forms:

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

const validator = new Validator({ language: 'es' });
const { valid, errors } = await validator.validate(
  { email: 'ana@example', age: '12' },
  { email: 'required|email', age: 'integer|min:18' },
);
// errors: { email: 'Introduce un email válido.', age: 'El valor debe ser 18 o mayor.' }

validator.validateValue(value, rules, context) validates a single value and returns the message, or ''.

Properties

The form also has the DileForm properties validationMessages, language and novalidate.

Methods

DileFormValidation demos

Signup form

<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/checkbox/checkbox.js';
  import '@dile/ui/components/button/button.js';

  class DemoSignupForm extends DileFormValidation(DileForm(LitElement)) {
    static validations = {
      email: 'email|maxLength:120',
      age: ['integer', ['between', 18, 120]],
      password: 'minLength:8',
      password_confirmation: 'same:password',
    };

    static properties = { result: { type: String } };

    render() {
      return html`
        <dile-input name="email" label="Email" required></dile-input>
        <dile-input name="age" label="Age"></dile-input>
        <dile-input name="password" label="Password" type="password" required></dile-input>
        <dile-input name="password_confirmation" label="Repeat password" type="password" required></dile-input>
        <dile-input name="code" label="Code (three uppercase letters)" validations="pattern:[A-Z]{3}" validate-on="input"></dile-input>
        <p><dile-checkbox name="terms" required>I accept the terms</dile-checkbox></p>
        <dile-button @click=${this.send}>Send</dile-button>
        <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('demo-signup-form', DemoSignupForm);
</script>
<demo-signup-form></demo-signup-form>