Capítulo 24 de 39

Chapter 24: trigger

Core Idea

trigger(name?, { shouldFocus? }) manually runs validation without submitting — returns Promise<boolean> resolving true if the targeted field(s) pass — useful for dependent-field validation and custom validate-on-demand flows.

Key Concepts

  • name: undefined (validate everything), a single field name, or an array of names.
  • shouldFocus (7.7.0+): focuses the field when an error results; only works with a real registered ref, not a custom/virtual registration.
  • Render-optimization scope: targeting a single field by string name keeps the re-render isolated to that field; passing an array or calling trigger() with no arguments re-renders the entire form's state.
  • Return value: Promise<boolean> — awaitable, so you can branch logic on whether validation passed.

Code Examples

const isValid = await trigger("firstName")       // single field, isolated re-render
await trigger(["firstName", "lastName"])          // multiple fields, whole-form re-render
await trigger()                                   // everything, whole-form re-render
trigger("name", { shouldFocus: true })            // focus on failure
  • What it demonstrates: the re-render-scope difference between single-name and multi-name/no-argument calls.

Anti-patterns

  • Expecting isolated re-renders when passing an array of names: only a single string name gets that optimization.
  • Relying on shouldFocus for a field registered without a real DOM ref: it silently does nothing.

Key Takeaways

  1. trigger is the on-demand validation entry point outside of a real submit — commonly used for dependent-field checks.
  2. Only a single-field string call gets the isolated re-render optimization; batch/whole-form triggers re-render everything.
  3. It's awaitable — use the resolved boolean to branch (e.g. before proceeding to a wizard's next step).

Connects To

  • useform-register: register's deps option triggers this automatically for dependent fields on that field's own validation, but not on a manual trigger() call.
  • useform-formstate: where the resulting errors/isValid land.