normalize()
Clean up common input formatting. Forgiving input.
Try it
Choose a format, edit the sample value and normalize it. Compare the original with the output. Formatting cleanup does not verify that an address or phone number is valid.
Choose a format, then normalize.
<div id="your-component">
<label>Format<select><option value="whitespace">Whitespace</option><option value="email">Email</option><option value="phone">Phone</option></select></label><label>Original value<input value=" A small idea "></label><button>Normalize value</button><div class="data-preview"><span class="muted">Cleaned output</span><output data-output>Waiting for input</output></div><p class="demo-status" role="status">Choose a format, then normalize.</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 input = el.querySelector('input');
const format = el.querySelector('select');
const samples = { whitespace: ' A small idea ', email: ' HELLO@EXAMPLE.COM ', phone: '+31 (0) 6 1234 5678' };
format.addEventListener('change', () => { input.value = samples[format.value]; }, { signal });
el.querySelector('button').addEventListener('click', () => {
el.querySelector('output').textContent = kit.normalize[format.value](input.value);
status('Formatting cleaned. Validate this value separately before using it.');
}, { signal });
}
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
Use the pure whitespace(), email() and phone() helpers to clean common formatting. Each returns a string; email trims and lowercases only the domain, while phone removes common separators.
- Interface
whitespace, email, phone; not full validation.- Lifecycle
- These helpers create no listeners or timers, so there is no destroy step. Apply the returned value explicitly on blur or submission.
Accessibility and safety
Implementation notes
Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.
Normalization is not validation. Avoid rewriting text on every keystroke because that can move the caret or interrupt composition. Preserve email local-part casing.
What to check
Try extra spaces, a mixed-case email local part and formatted phone numbers. Confirm invalid data is still validated and typing is not interrupted.
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); } };
}