fieldValidation()
Show an error after someone edits a field. Validate after blur, then on correction.
Try it
Enter “hello”, then move out of the email field. An error appears after blur. Correct it to “hello@example.com” and the error clears as you type.
Start typing, then leave the field.
<div id="your-component">
<form novalidate class="sample-form"><span class="sample-label">Newsletter signup</span><label>Email address<input type="email" required placeholder="you@example.com" aria-describedby="validation-hint validation-error" autocomplete="email"></label><p id="validation-hint" class="field-hint">A sample form. No email is sent.</p><p id="validation-error" class="field-error" aria-live="polite"></p><button type="submit">Subscribe</button></form><p class="demo-status" role="status">Start typing, then leave the field.</p>
</div>import * as kit from 'subtly';
const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
function setup() {
const form = el.querySelector('form');
const input = el.querySelector('input');
const error = el.querySelector('.field-error');
const validation = kit.fieldValidation(input, {
validate(value, field) {
if (!value.trim()) return 'Enter your email address.';
return field.validity.typeMismatch ? 'Use an email like you@example.com.' : '';
},
render(message, field) {
error.textContent = message;
field.setAttribute('aria-invalid', String(Boolean(message)));
}
});
form.addEventListener('submit', event => {
event.preventDefault();
if (validation.check()) status('Email accepted in this local example. Nothing was sent.');
else { input.focus(); status('Check your email address.'); }
}, { signal });
return () => validation.destroy();
}
const stop = setup();
// Call when this component is removed.
function cleanup() {
listeners.abort();
stop?.();
}Add it to your project
- Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
- Connect the behavior. Copy the JavaScript tab, update
#your-componentand initialize it after the elements exist. Replace simulated operations with your own data. - Clean up on unmount. Call the example’s
cleanup()when the component is removed. It aborts application listeners and releases the utility’s timers or observers.
The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.
API and lifecycle
Provide a field plus validate(value, field) and render(message, field). Validation starts after the first blur or explicit check(), then runs during correction. Return an error string or an empty string from validate.
- Interface
field, validate, render; check/reset/destroy.- Lifecycle
- check() marks the field touched and returns whether it is valid. reset() clears its touched state and rendered error. destroy() removes the blur, input and composition listeners.
Accessibility and safety
Implementation notes
Always validate at submission and on the server. Keep values after failure.
The render callback owns visible error text, aria-invalid and aria-describedby. Validate on submit and on the server too; preserve entered values after failures.
What to check
Submit an empty field, correct it, and verify the error clears. Test keyboard navigation, screen-reader error association and text composition.
View documented module source
/** Validate after first blur/submission, then immediately while correcting.
* validate(value, field) returns an error string or empty string.
* render(message, field) owns error text, aria-invalid and aria-describedby.
* Never replace server validation. Use explicit submit validation as well. */
export function fieldValidation(field, { validate, render }) {
let touched = false;
function check() { const message = validate(field.value, field) || ''; render(message, field); return !message; }
function blur() { touched = true; check(); }
function input(event) { if (touched && !event.isComposing) check(); }
field.addEventListener('blur', blur);
field.addEventListener('input', input);
field.addEventListener('compositionend', input);
return { check() { touched = true; return check(); }, reset() { touched = false; render('', field); }, destroy() {
field.removeEventListener('blur', blur); field.removeEventListener('input', input); field.removeEventListener('compositionend', input);
}};
}
/** Pure normalization helpers. Use on blur or server submission, not on
* every keystroke (which can break caret position and IME input).
* Email local parts are intentionally not lowercased. */
export const normalize = {
whitespace: value => value.trim().replace(/\s+/gu, ' '),
email(value) { const s = value.trim(), i = s.lastIndexOf('@'); return i < 0 ? s : s.slice(0,i+1) + s.slice(i+1).toLowerCase(); },
phone(value) { return value.trim().replace(/[\s().-]/g, ''); }
};
/** Focus first invalid field after submission; avoids focusing hidden inputs.
* For custom widgets, supply a selector matching their focusable trigger. */
export function focusInvalid(form, selector = '[aria-invalid="true"], :invalid') {
const field = [...form.querySelectorAll(selector)].find(e => typeof e.focus === 'function' && e.getClientRects().length && !e.disabled && !e.closest('[inert]'));
field?.focus();
return field || null;
}
/** Warn on browser navigation only while a form has unsaved edits.
* SPA/Livewire route guards need separate integration. Browsers control
* the warning text and may suppress it, especially on mobile. */
export function unsavedChanges() {
let dirty = false;
function warn(e) { e.preventDefault(); e.returnValue = true; }
function set(value) { if (dirty === Boolean(value)) return; dirty = Boolean(value); if (dirty) window.addEventListener('beforeunload', warn); else window.removeEventListener('beforeunload', warn); }
return { set, get dirty() { return dirty; }, destroy() { set(false); } };
}