focusInvalid()
Move to the first invalid field.
Try the example
Submit the empty project form. Focus moves to the first missing field. Fill the title, submit again and focus moves to the email field.
Both fields are required. Nothing is submitted.
Add it to your project
- Copy the HTML. Place the markup inside the component where this behavior belongs. The preview’s visual classes are website styles; use your own design system.
- Connect the behavior. Copy the JavaScript tab and call its exported
mount(element)after your component’s elements exist. Replace simulated delays and data operations with your own application code. - Clean up. Call the returned cleanup when the component unmounts. It aborts the example’s listeners and releases the helper’s timers, observers or state.
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.