Subtlyv0.1.1
Forms & drafts

focusInvalid()

Move to the first invalid field. Focus visible invalid field.

Available in v0.1.1forms.jsForms

Try it

Submit the empty project form. Focus moves to the first missing field. Fill the title, submit again and focus moves to the email field.

Live example

Both fields are required. Nothing is submitted.

<div id="your-component">
<form novalidate class="sample-form"><label>Project title<input name="title" required aria-describedby="project-title-error"></label><p class="field-error" id="project-title-error"></p><label>Contact email<input name="email" type="email" required aria-describedby="project-email-error"></label><p class="field-error" id="project-email-error"></p><button type="submit">Create sample project</button></form><p class="demo-status" role="status">Both fields are required. Nothing is submitted.</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');
          form.addEventListener('submit', event => {
            event.preventDefault();
            for (const field of form.querySelectorAll('input')) {
              const invalid = !field.validity.valid;
              field.setAttribute('aria-invalid', String(invalid));
              const error = el.querySelector('#' + field.getAttribute('aria-describedby'));
              error.textContent = invalid ? (field.validity.valueMissing ? 'Complete this field.' : 'Enter a valid email address.') : '';
            }
            if (!form.checkValidity()) {
              kit.focusInvalid(form); status('Focus moved to the first field that needs attention.');
            } else status('Sample project is valid. No data was submitted.');
          }, { signal });
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. 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.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. 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

Call focusInvalid(form) after a failed submission. It finds the first matching invalid field that is visible, enabled and outside inert content, focuses it and returns that element, or null.

Interface
form, optional selector.
Lifecycle
This is a one-off operation with no persistent listeners. For custom widgets, pass a selector matching the widget's focusable trigger rather than its hidden backing input.

Accessibility and safety

Implementation notes

Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.

Moving focus is only part of error recovery. Keep a visible error message associated with the field, preserve values and validate on the server.

What to check

Submit multiple invalid fields and confirm the first visible field receives focus. Hidden, disabled and inert controls should be skipped.

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); } };
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close