Repository navigation
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.
<link rel="stylesheet" href="/assets/pair.css">
<script src="/assets/PairValidation.js" defer></script>Global object:
window.PairValidationThe script boots automatically on DOMContentLoaded and scans the document for preset-backed fields and opt-in 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>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-invalidand appends the error ID toaria-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-describedbytokens - 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.
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:
- field-specific message
- form-specific message such as
data-pair-validation-message-required - global message configured in JavaScript
- built-in Italian or English message
- the browser message as a last fallback
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-summaryenables 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-anchorselects a wrapper after which the error should be inserted -
data-pair-validation-groupgroups checkbox, radio, or custom field markup
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.
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.
-
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).
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
The following bubbling CustomEvent values are dispatched:
pair:validation:field-invalidpair:validation:field-validpair:validation:form-invalidpair:validation:form-valid
Form events include detail.fields. Invalid form events also include detail.source with client or server.
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-presetdata-pair-validation-message- preset defaults such as
minlength,maxlength,pattern,placeholder,inputmode, andautocompletewhen supported and not already set
With PairValidation.js loaded, the field is normalized on input/change and invalid values are reported through setCustomValidity(...).
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);Supported canonical presets:
bice164_phoneean13emailhex_coloribanip_addressipv4_addressipv6_addressmac_addressslugurluuidit.fiscal_codeit.personal_fiscal_codeit.sdi_recipient_codeit.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.
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.
Binds one field to the preset from field.dataset.pairValidationPreset.
Pass forcedPreset when the preset should be controlled by code instead of markup.
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();
}Normalizes and validates a value with a canonical preset or alias.
Empty values are valid unless required is true.
Normalizes a value with the selected preset and returns a string.
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(...).
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-invalidclass 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.
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.
- Client-side checks are UX hints only. Keep
FormControl::preset(...), a preset-backedFormhelper, or equivalent server-side validation. - Unknown presets are ignored by binding helpers and return
falsefromisValid(...). -
data-pair-validation-messageremains the preset/custom-error message; constraint-specific overrides usedata-pair-validation-message-{rule}.
See also: FormValidationPreset, FormControl, Form, PairUI.js.
Maintained by Viames Marino — VM Ingegneria · Professional enquiries
Home · Setup · Configuration
Build with Pair 4
- Generator
- Controllers and responses
- Read models
- ActiveRecord and queries
- Forms and validation
- PairUI.js, PairMotion.js and HTML fragments
APIs and authentication
- API guide and CRUD
- Middleware and rate limits
- Users, sessions, and ACL
- Passkeys and social login
- Native mobile setup
Integrate and operate
- Integrations
- Runtime extensions and adapter keys
- Cache and cache stores
- Logs and observability
- PWA and push
- Packages and distribution
- Upgrade to v4