Introduction
Read Validation first for the contract itself — the three properties, one event and two methods every form component shares. Every recipe below has the same shape:
- Listen for
aegovValidate, or callvalidate()yourself. - Decide, in your own code, whether the value is acceptable.
- Write the answer back with
isInvalid+errorMessage, or withsetCustomValidity().
<aegov-input id="eid" name="emiratesId" hint="15 digits, as printed on your card"></aegov-input>
<script type="module">
const eid = document.querySelector('#eid');
eid.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger === 'input') return;
// Accept Arabic-Indic digits (١٢٣) from an Arabic keyboard as well as 0–9.
const digits = String(e.detail.value)
.replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x0660))
.replace(/\D/g, '');
const ok = digits.length === 15;
eid.isInvalid = !ok;
eid.errorMessage = ok ? '' : 'Emirates ID must be 15 digits';
});
</script>
The two fields below show the result: a valid Emirates ID keeps its hint, and a short one shows the error.
Choosing when to validate
Gate on detail.trigger. It tells you what the user just did, and validating at the wrong moment is the most common reason a form feels hostile.
| Trigger | Validate here? | Why |
|---|---|---|
input |
Rarely | Fires on every keystroke. Telling someone their email is invalid while they are typing it is noise. Use it only for live feedback such as a password strength meter or a character count. |
change |
Sometimes | Good for discrete choices — a select, a checkbox, a date. The value is committed, so a verdict is fair. |
blur |
Usually | The user has finished with the field and moved on. The default moment to judge a typed value. |
submit |
Always | The last line of defence. Validate everything, whatever the user touched. |
manual |
Your call | You called validate(), so you already know why. |
A good default: validate on blur, then re-validate on input only once the field has already shown an error, so a correction clears the message straight away.
let hasErrored = false;
field.addEventListener('aegovValidate', (e) => {
const { trigger, value } = e.detail;
if (trigger === 'input' && !hasErrored) return;
const ok = myRule(value);
hasErrored = !ok;
field.isInvalid = !ok;
field.errorMessage = ok ? '' : 'Enter a valid value';
});
Recipe — a reusable field rule
Rather than repeating listeners, write one helper and point it at a rule.
/**
* Attach a rule to any aegov form component.
* @param el the aegov-* element
* @param rule (value) => string | null — return a message, or null when valid
*/
function attachRule(el, rule) {
let errored = false;
el.addEventListener('aegovValidate', (e) => {
const { trigger, value } = e.detail;
if (trigger === 'input' && !errored) return;
const message = rule(value);
errored = message !== null;
el.isInvalid = errored;
el.errorMessage = message ?? '';
});
}
// Arabic-Indic digits (١٢٣) to 0–9, so users with an Arabic keyboard pass the digit rules too.
const toLatinDigits = (v) => String(v).replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x0660));
attachRule(document.querySelector('#email'), (v) =>
/\S+@\S+\.\S+/.test(v) ? null : 'Enter a valid email address');
attachRule(document.querySelector('#eid'), (v) =>
toLatinDigits(v).replace(/\D/g, '').length === 15 ? null : 'Emirates ID must be 15 digits');
attachRule(document.querySelector('#mobile'), (v) =>
/^(\+971|0)?5\d{8}$/.test(toLatinDigits(v).replace(/[\s-]/g, '')) ? null : 'Enter a UAE mobile number');
attachRule(document.querySelector('#terms'), (v) =>
v === true ? null : 'You must accept the terms to continue');
Note the last one: aegov-checkbox reports a boolean, not a string. Check the Value types table on Validation before writing a rule — aegov-range in range mode gives you { low, high }, aegov-fileupload gives you File[], and aegov-datepicker in range appearance gives you { start, end }.
Rules written this way only change what is shown. If the rule must also stop the form from submitting, or you use the shared listener from the whole-form recipe, write it with setCustomValidity() instead — see the comparison under server-side checks below.
Recipe — required fields without a library
is-required already makes the component report valueMissing when it is empty. So for required fields you usually only need to show the flag, not write a rule:
field.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger === 'input') return;
if (e.detail.validity.valueMissing) {
field.isInvalid = true;
field.errorMessage = 'This field is required';
return;
}
field.isInvalid = false;
field.errorMessage = '';
});
Reading detail.validity also lets the component do the work for type="email", pattern, length and min / max — you only supply the wording:
function messageFor(el, detail) {
const v = detail.validity;
if (v.valid) return '';
if (v.customError) return detail.validationMessage; // set with setCustomValidity()
if (v.valueMissing) return 'This field is required';
if (v.typeMismatch) return el.localName === 'aegov-fileupload' ? 'Choose an allowed file type'
: el.type === 'url' ? 'Enter a valid web address' : 'Enter a valid email address';
if (v.tooShort) return 'Too short';
if (v.tooLong) return el.localName === 'aegov-fileupload' ? 'Choose a smaller file' : 'Too long';
if (v.rangeUnderflow) return 'Choose a later date';
if (v.rangeOverflow) return 'Choose an earlier date';
if (v.patternMismatch) return 'Use the required format';
return 'Check this field';
}
field.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger === 'input') return;
const message = messageFor(field, e.detail);
field.isInvalid = !!message;
field.errorMessage = message;
});
This is the cheapest useful validation in the system: no rules of your own, accurate flags, your own wording.
Recipe — whole-form validation on submit
Show each field's error whenever it is validated, then on submit call validate('submit') on every control, stop if anything failed, and move focus to the first problem.
<form id="application" novalidate>
<aegov-form-field>
<aegov-label>Full name</aegov-label>
<aegov-input id="fullName" name="fullName" is-required></aegov-input>
</aegov-form-field>
<aegov-form-field>
<aegov-label>Email address</aegov-label>
<aegov-input id="email" name="email" type="email" is-required></aegov-input>
</aegov-form-field>
<aegov-form-field>
<aegov-label>Preferred appointment</aegov-label>
<aegov-datepicker id="appointment" name="appointment" is-required></aegov-datepicker>
</aegov-form-field>
<aegov-checkbox id="terms" name="terms" is-required label="I accept the terms of service"></aegov-checkbox>
<aegov-button type="submit" variant="primary" size="lg">Submit application</aegov-button>
</form>
<script type="module">
const FORM_CONTROLS = [
'aegov-input', 'aegov-textarea', 'aegov-select',
'aegov-checkbox', 'aegov-checkbox-group',
'aegov-radio', 'aegov-radio-group', 'aegov-toggle', 'aegov-range',
'aegov-otp', 'aegov-fileupload', 'aegov-datepicker',
].join(', ');
const form = document.querySelector('#application');
// messageFor() is the helper from the required-fields recipe above.
// It keeps messages set with setCustomValidity() as they are.
form.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger === 'input') return;
e.target.isInvalid = !e.detail.validity.valid;
e.target.errorMessage = messageFor(e.target, e.detail);
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const controls = [...form.querySelectorAll(FORM_CONTROLS)];
const results = await Promise.all(controls.map((c) => c.validate('submit')));
const failedIndex = results.findIndex((r) => !r.valid);
if (failedIndex !== -1) {
const failed = controls[failedIndex];
// A checkbox or radio group takes focus on its first option.
(failed.querySelector('aegov-checkbox, aegov-radio') ?? failed).focus();
return;
}
const data = new FormData(form);
await api.submitApplication(data);
});
</script>
Three details worth keeping:
- The
aegovValidatelistener on the form is what puts each error under its field.validate()only reports problems; without the listener the submit would stop and move focus, but no field would show why. novalidateon the form turns off the browser's own error bubbles, so your messages are the only ones shown. The checks still run.Promise.all, not a loop withawaitinside. Validation is asynchronous on every component; running the checks together keeps submit responsive on long forms.
Recipe — a form-level error summary
A single field announces its own error. A form with several failures also needs a summary at the top — government services are usually required to provide one. Build on the whole-form recipe above: keep its FORM_CONTROLS list and its aegovValidate listener, add the summary markup at the top of the form, and replace its submit handler with the one below.
<div id="summary" tabindex="-1" hidden>
<aegov-callout variant="error">
<p class="font-bold">There are problems with your application</p>
<ul id="summary-list" class="list-disc ps-5"></ul>
</aegov-callout>
</div>
// The field's visible label, so each entry says which field it is about.
function labelOf(el) {
const label = el.closest('aegov-form-field')?.querySelector('aegov-label')?.textContent ?? el.label ?? '';
return label.trim();
}
async function validateAll(form) {
const controls = [...form.querySelectorAll(FORM_CONTROLS)];
const results = await Promise.all(controls.map((c) => c.validate('submit')));
return controls
.map((el, i) => ({ el, result: results[i] }))
.filter(({ result }) => !result.valid);
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
const failures = await validateAll(form);
const summary = document.querySelector('#summary');
const list = document.querySelector('#summary-list');
if (failures.length === 0) {
summary.hidden = true;
return api.submitApplication(new FormData(form)); // your own submit function
}
list.replaceChildren(
...failures.map(({ el, result }) => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = `#${el.id}`;
const message = messageFor(el, { validity: result.validity, validationMessage: result.message });
const label = labelOf(el);
a.textContent = label ? `${label}: ${message}` : message;
a.addEventListener('click', (ev) => {
ev.preventDefault();
// A checkbox or radio group takes focus on its first option.
(el.querySelector('aegov-checkbox, aegov-radio') ?? el).focus();
});
li.append(a);
return li;
}),
);
summary.hidden = false;
summary.focus();
});
Each entry names its field ("Full name: This field is required") and links to it by the control's id, moving focus there when activated. After a failed submit, focus moves to the summary (that is what tabindex="-1" is for), so keyboard and screen reader users start from the list of problems. The error callout already has role="alert", so do not add another one. The summary uses your own messageFor() wording rather than result.message, which for built-in problems is the browser's text in the browser's language.
Recipe — cross-field rules
Put a cross-field rule on the field the user can fix, and re-run it when either field changes.
<aegov-input id="password" name="password" type="password" is-revealable></aegov-input>
<aegov-input id="confirm" name="confirmPassword" type="password" is-revealable></aegov-input>
const password = document.querySelector('#password');
const confirm = document.querySelector('#confirm');
function checkMatch() {
if (!confirm.value) return; // nothing to judge yet
const ok = password.value === confirm.value;
confirm.isInvalid = !ok;
confirm.errorMessage = ok ? '' : 'Passwords do not match';
}
confirm.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger !== 'input') checkMatch();
});
// Re-check the confirmation when the source field changes
password.addEventListener('aegovValidate', () => checkMatch());
Date ranges follow the same shape. A single aegov-datepicker with appearance="range" already gives you both ends in one value, so a single-field rule is enough there — this pattern is for two separate pickers:
function checkOrder() {
if (!startDate.value || !endDate.value) return;
const ok = new Date(endDate.value) >= new Date(startDate.value);
endDate.isInvalid = !ok;
endDate.errorMessage = ok ? '' : 'The end date must be on or after the start date';
}
startDate.addEventListener('aegovValidate', () => checkOrder());
endDate.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger !== 'input') checkOrder();
});
Recipe — server-side and async checks
Use setCustomValidity() for anything the browser cannot know. It marks the field invalid, shows the message and blocks submission in one call; an empty string clears it. Debounce the request, and ignore responses that arrive after a newer check started.
const username = document.querySelector('#username');
let timer;
let requestId = 0;
username.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger === 'input') return;
const value = String(e.detail.value).trim();
clearTimeout(timer);
if (!value) {
username.setCustomValidity('');
return;
}
const id = ++requestId;
timer = setTimeout(async () => {
username.hint = 'Checking availability…';
try {
// Replace with your own endpoint
const res = await fetch(`/api/username-available?u=${encodeURIComponent(value)}`);
const { available } = await res.json();
if (id !== requestId) return; // a newer check superseded this one
await username.setCustomValidity(available ? '' : 'That username is already taken');
username.hint = available ? 'This username is available' : '';
} catch {
if (id !== requestId) return;
username.hint = '';
await username.setCustomValidity('We could not check availability. Try again.');
}
}, 400);
});
For a server rejection that arrives after submit, write it back onto the field it belongs to and move focus there:
try {
await api.submitApplication(data);
} catch (err) {
if (err.fieldErrors) {
for (const [name, message] of Object.entries(err.fieldErrors)) {
const el = form.querySelector(`[name="${name}"]`);
await el?.setCustomValidity(message);
}
form.querySelector(`[name="${Object.keys(err.fieldErrors)[0]}"]`)?.focus();
}
}
setCustomValidity() or isInvalid + errorMessage?
| Use | When |
|---|---|
setCustomValidity(message) |
The error comes from outside the browser — a server response, an async check, a business rule — or it must stop the form from submitting. It sets validity.customError, makes validate() report the field as invalid, and keeps the field invalid in form.checkValidity() until you clear it or the form is reset (checkbox and radio groups excepted — only their validate() reports it). |
isInvalid + errorMessage |
You only want to change what is shown, driven from your own state. validate() and the form still go by the field's built-in constraints. |
When in doubt, prefer setCustomValidity() — it keeps what the form knows in step with what the user sees.
Recipe — let the browser decide
If your rules can be written as attributes, let the components decide and only supply the wording. aegov-input accepts pattern, minlength, maxlength, min, max and step; aegov-textarea accepts maxlength; aegov-otp accepts pattern; aegov-datepicker accepts min and max.
<aegov-textarea
name="reason"
maxlength="500"
is-required
hint="Up to 500 characters"
></aegov-textarea>
<aegov-otp name="code" length="6" pattern="^\d{6}$"></aegov-otp>
<aegov-datepicker name="appointment" min="2026-09-01" max="2026-12-31"></aegov-datepicker>
for (const el of form.querySelectorAll(FORM_CONTROLS)) {
el.addEventListener('aegovValidate', (e) => {
if (e.detail.trigger === 'input') return;
el.isInvalid = !e.detail.validity.valid;
el.errorMessage = messageFor(el, e.detail);
});
}
When you do not need a message per field, form.checkValidity() works as a single gate for every form-associated control (checkbox and radio groups excepted — call their validate()):
if (!form.checkValidity()) return; // something is invalid
Recipe — translated messages
Keep messages in a lookup keyed by rule rather than inline in each listener, so a second language is a data change rather than a code change.
const MESSAGES = {
en: {
required: 'This field is required',
email: 'Enter a valid email address',
emiratesId: 'Emirates ID must be 15 digits',
mobile: 'Enter a UAE mobile number',
tooShort: ({ min }) => `Use at least ${min} characters`,
},
ar: {
required: 'هذا الحقل مطلوب',
email: 'أدخل بريدًا إلكترونيًا صحيحًا',
emiratesId: 'يجب أن تكون الهوية الإماراتية ١٥ رقمًا',
mobile: 'أدخل رقم هاتف متحرك إماراتي',
tooShort: ({ min }) => `استخدم ${min} أحرف على الأقل`,
},
};
function t(key, params) {
const locale = document.documentElement.lang === 'ar' ? 'ar' : 'en';
const entry = MESSAGES[locale][key];
return typeof entry === 'function' ? entry(params ?? {}) : entry;
}
attachRule(email, (v) => (/\S+@\S+\.\S+/.test(v) ? null : t('email')));
Do not show el.validationMessage (or detail.validationMessage) for built-in problems. The browser writes that text in the browser's language, not your page's, so an Arabic page in an English browser would show English errors you never wrote.
RTL considerations
Nothing on this page changes under dir="rtl" — validation is behaviour, and the components handle mirroring themselves. Two things deserve attention:
- Write real Arabic copy, not transliterations. Error messages carry the whole accessible meaning of the invalid state, so a machine-translated string is an accessibility problem, not a cosmetic one.
- Numerals. Arabic-Indic digits (
١٢٣) read naturally in Arabic prose, but the value a user types into an Emirates ID field is Western digits. Users with an Arabic keyboard may still type Arabic-Indic digits, so convert them before checking a value, as the Emirates ID rule above does. Show input requirements in Western digits and use Arabic-Indic numerals only in prose.
Accessibility
Built in
The components already do this — do not re-implement it:
aria-invalidon the inner control, driven byis-invalid.aria-describedbyon the inner control pointing at the hint and error. Anaria-describedbyyou set on the component cannot reach text elsewhere on the page, so put extra help text in thehintslot.- The error region's
role="alert"held back until the user first leaves the field or a submit finds it invalid, so nothing is announced mid-typing. - An
is-invalidclass on the host for your own styling.
Your responsibilities
- Never signal an error with colour alone (WCAG 2.2 SC 1.4.1). Always set
error-messageor fill theerrorslot; the red border is decoration on top of the text, not a substitute for it. - Say what to do. "Enter a date on or after 1 September 2026" beats "Invalid date".
- Move focus to the first invalid control on a failed submit. The components will not do this for you.
- Provide a form-level summary for multi-field failures, announced when it appears, with links that move focus to each field.
- Do not disable the submit button as the only feedback while the form is invalid. A disabled button gives keyboard and screen reader users nothing to act on and no explanation. Let them submit, then explain what failed.
- Keep each message next to its field, which the components do for you.
Where to next
- Validation — the contract, value types, form integration and accessibility.
- Component pages with the most validation options: Input, Select, Datepicker, File upload and OTP.
- Form field — the wrapper and its cascade.