Skip to content

PairValidation.js

Viames Marino edited this page Jul 24, 2026 · 2 revisions

Pair framework: PairValidation.js

/assets/PairValidation.js is Pair's progressive browser validator. It provides two compatible layers:

  • reusable field presets from FormValidationPreset
  • accessible, customizable form validation for forms marked with data-pair-validate

The full-form layer uses the browser Constraint Validation API, renders actionable inline errors, maintains ARIA relationships, and supports custom widgets without requiring jQuery.

Installation

<link rel="stylesheet" href="/assets/pair.css">
<script src="/assets/PairValidation.js" defer></script>

Global object:

window.PairValidation

The script boots automatically on DOMContentLoaded and scans the document for preset-backed fields and opt-in forms.

Accessible form validation

Quick start with Pair forms

Enable the validator explicitly on each form that should use it:

$form = (new \Pair\Html\Form())
    ->action('/contracts/save')
    ->clientValidation();

$form->text('customerName')
    ->label('Customer name')
    ->required()
    ->requiredMessage('Enter the customer name.');

Form::clientValidation() renders the boolean data-pair-validate attribute. It intentionally does not render novalidate. The script sets form.noValidate = true only after it has initialized successfully, so native browser validation remains available if JavaScript fails to load.

Plain HTML can opt in directly:

<form data-pair-validate>
  <label for="customer-name">Customer name</label>
  <input
    id="customer-name"
    name="customerName"
    required
    data-pair-validation-message-required="Enter the customer name."
  >
  <button type="submit">Save</button>
</form>

Default interaction

The validator:

  • validates a field after it has been touched, without showing every error on page load
  • validates the whole form on submit and moves focus to the first invalid field
  • places each correction immediately after the native control or supported custom widget
  • sets aria-invalid and appends the error ID to aria-describedby
  • announces the aggregate error count through one polite live region
  • removes errors as the user corrects the value
  • uses invalid styling only and does not add a distracting positive state
  • preserves existing aria-describedby tokens
  • respects disabled controls, formnovalidate, native form reset, reduced motion, forced colors, and increased contrast

Server-side validation remains mandatory. This helper improves recovery in the browser but does not enforce authorization, ownership, business rules, or data integrity.

Message customization

Use requiredMessage(...) for the most common case:

$form->select('affiliateId')
    ->required()
    ->requiredMessage('Select an affiliate.');

Use validationMessage(...) for another HTML validity rule:

$form->email('email')
    ->required()
    ->validationMessage('Enter a valid work email address.', 'type');

$form->text('reference')
    ->minLength(3)
    ->validationMessage('Use at least {minLength} characters.', 'minLength');

Supported rule names are required, type, pattern, minLength, maxLength, min, max, step, badInput, and custom. Pair converts camelCase rule names to kebab-case data attributes, for example minLength becomes data-pair-validation-message-min-length.

Messages can use these placeholders when applicable:

  • {label}
  • {minLength} and {maxLength}
  • {min} and {max}
  • {count}

The resolution order is:

  1. field-specific message
  2. form-specific message such as data-pair-validation-message-required
  3. global message configured in JavaScript
  4. built-in Italian or English message
  5. the browser message as a last fallback

Form options

The default locale follows the form lang, the document lang, and then the browser locale. Override it per form when needed:

<form
  data-pair-validate
  data-pair-validation-locale="it"
  data-pair-validation-summary
  data-pair-validation-focus="summary"
>
  <!-- Form controls. -->
</form>

Available form attributes:

  • data-pair-validation-locale="it|en" selects built-in messages
  • data-pair-validation-summary enables a linked summary at the start of the form
  • data-pair-validation-focus="first-invalid|summary|none" selects the recovery focus target
  • data-pair-validation-message-{rule} provides one form-wide rule message

Available field or wrapper attributes:

  • data-pair-validation-ignore="true" excludes a field
  • data-pair-validation-anchor selects a wrapper after which the error should be inserted
  • data-pair-validation-group groups checkbox, radio, or custom field markup

Global configuration

Configure defaults once in the application bootstrap:

// Configures defaults shared by all subsequently validated forms.
PairValidation.configure({
  locale: 'it',
  focusTarget: 'first-invalid',
  summary: false,
  messages: {
    required: 'Completa “{label}”.',
    summaryOne: 'Correggi il campo indicato',
    summaryMany: 'Correggi {count} campi'
  }
});

Message entries may also be functions receiving the interpolation context.

Server-side and asynchronous errors

Render a single external error through the same UI:

// Applies an asynchronous uniqueness error to one field.
PairValidation.setFieldError(
  document.querySelector('[name="account"]'),
  'This account already exists.'
);

Apply an error object keyed by field name:

// Applies Problem Details or application errors after an AJAX response.
PairValidation.setServerErrors(form, {
  account: 'This account already exists.',
  customerName: ['Enter the registered name.', 'Do not use abbreviations.']
});

setServerErrors(...) returns false when at least one error was applied and accepts {focus: false} when the caller must preserve focus. An external error is cleared when the user edits that field.

Lifecycle methods

  • bindForm(form) initializes one opt-in form
  • validateField(field, options = {}) returns the field validity and optionally renders its error
  • validateForm(form, options = {}) returns the form validity and optionally moves focus
  • clearField(field) removes Pair-owned feedback for one field
  • resetForm(form) clears all Pair-owned form state
  • destroyForm(form) removes listeners and restores the previous native validation state

bindDocument(root) binds both presets and opt-in forms in a newly inserted region. Pair also listens for the framework-level pair:region:replaced event. Applications with their own replacement event should bridge it to bindDocument(event.detail.root).

Custom widget adapters

Select2 and NiceSelect2 are supported automatically when their generated widget is present. Pair observes their visible value so feedback is refreshed even when the widget library emits only library-specific events. Register another widget once from the application bootstrap:

// Maps a custom widget to its visual, focus, and insertion elements.
PairValidation.registerAdapter('custom-combobox', {
  matches(field) {
    return field.matches('select[data-custom-combobox]');
  },
  resolve(field) {
    const widget = field.nextElementSibling;

    return {
      anchor: widget,
      focus: widget.querySelector('[role="combobox"]'),
      visual: widget
    };
  }
});

An adapter must expose matches(field) and resolve(field). resolve(...) returns:

  • anchor: element after which the message is inserted
  • focus: element that receives focus and ARIA feedback
  • visual: element that receives invalid styling

Validation events

The following bubbling CustomEvent values are dispatched:

  • pair:validation:field-invalid
  • pair:validation:field-valid
  • pair:validation:form-invalid
  • pair:validation:form-valid

Form events include detail.fields. Invalid form events also include detail.source with client or server.

Server-generated usage

The usual path is to let Form and FormControl generate the right attributes:

$form = new \Pair\Html\Form();

$form->emailAddress('email')->required();
$form->iban('ibanCode');
$form->italianVatNumber('vatNumber');

FormControl::preset(...) adds:

  • data-pair-validation-preset
  • data-pair-validation-message
  • preset defaults such as minlength, maxlength, pattern, placeholder, inputmode, and autocomplete when supported and not already set

With PairValidation.js loaded, the field is normalized on input/change and invalid values are reported through setCustomValidity(...).

Manual HTML usage

You can also annotate plain HTML controls:

<input
  name="ibanCode"
  data-pair-validation-preset="iban"
  data-pair-validation-message="Enter a valid IBAN."
>

For dynamically inserted markup, call bindDocument(...) on the container:

// Binds preset fields inside a fragment rendered after page load.
PairValidation.bindDocument(fragment);

Presets

Supported canonical presets:

  • bic
  • e164_phone
  • ean13
  • email
  • hex_color
  • iban
  • ip_address
  • ipv4_address
  • ipv6_address
  • mac_address
  • slug
  • url
  • uuid
  • it.fiscal_code
  • it.personal_fiscal_code
  • it.sdi_recipient_code
  • it.vat_number

The same aliases accepted by FormValidationPreset::canonicalName(...) are accepted client-side, for example swift, email_address, partita_iva, piva, codice_fiscale, and sdi.

High-level methods

PairValidation.bindDocument(root = document)

Binds every field with data-pair-validation-preset and every form[data-pair-validate] inside a document or container. Use this after injecting server-rendered fragments or modal content.

PairValidation.bindPresetField(field, forcedPreset = null)

Binds one field to the preset from field.dataset.pairValidationPreset. Pass forcedPreset when the preset should be controlled by code instead of markup.

PairValidation.validatePresetFields(root = document, showState = false)

Validates every preset field inside root and returns true only if all fields are valid. When showState is true, the script updates the visible invalid state immediately.

const valid = PairValidation.validatePresetFields(form, true);

if (!valid) {
  // Let the existing form flow stop or focus the first invalid field.
  form.reportValidity();
}

PairValidation.isValid(preset, value, required = false)

Normalizes and validates a value with a canonical preset or alias. Empty values are valid unless required is true.

PairValidation.normalize(preset, value)

Normalizes a value with the selected preset and returns a string.

Field-specific helpers

The script exports binding helpers:

  • bindBicField(...)
  • bindE164PhoneField(...)
  • bindEan13Field(...)
  • bindEmailAddressField(...)
  • bindHexColorField(...)
  • bindIbanField(...)
  • bindIpAddressField(...)
  • bindIpv4AddressField(...)
  • bindIpv6AddressField(...)
  • bindMacAddressField(...)
  • bindSlugField(...)
  • bindUrlField(...)
  • bindUuidField(...)
  • bindItalianFiscalCodeField(...)
  • bindItalianPersonalFiscalCodeField(...)
  • bindItalianSdiRecipientCodeField(...)
  • bindItalianVatNumberField(...)

It also exports matching validators and normalizers such as isValidIban(...), normalizeIban(...), isValidItalianVatNumber(...), and normalizeItalianVatNumber(...).

Browser behavior

When a preset field is bound:

  • values are normalized on input and change events
  • EAN-13 fields can complete twelve-digit UPC-A values with a leading zero on change
  • invalid values call setCustomValidity(...) with the field message or preset default
  • Bootstrap's is-invalid class is toggled for invalid state only
  • a non-opt-in parent form gets a submit listener that refreshes preset validity before native form reporting

On form[data-pair-validate], the full form validator owns feedback, focus recovery, and inline error rendering while reusing preset custom validity. The helper does not add a positive valid class.

Compatibility alias

For older fiscal-identity integrations, the script also exposes window.EpFiscalIdentity when that object does not already exist. It maps the Italian fiscal-code, VAT number, SdI recipient-code, IBAN, and EAN-13 helpers to the newer PairValidation implementation.

Notes

  • Client-side checks are UX hints only. Keep FormControl::preset(...), a preset-backed Form helper, or equivalent server-side validation.
  • Unknown presets are ignored by binding helpers and return false from isValid(...).
  • data-pair-validation-message remains the preset/custom-error message; constraint-specific overrides use data-pair-validation-message-{rule}.

See also: FormValidationPreset, FormControl, Form, PairUI.js.

Clone this wiki locally