Capítulo 13 de 29

Chapter 13: Linked Fields (Cross-Field Validation)

Core Idea

onChangeListenTo/onBlurListenTo declare which other fields' changes should re-trigger this field's validator — the mechanism behind classics like "confirm password must match password."

Key Concepts

  • Without onChangeListenTo, a field's onChange validator only re-runs when that field itself changes — editing "password" alone won't re-validate an already-filled "confirm password" field.
  • onChangeListenTo: ['password'] on the confirm_password field's validators makes editing password re-trigger confirm_password's onChange validator.
  • Inside that validator, reach the other field's live value via fieldApi.form.getFieldValue('password').
  • onBlurListenTo is the blur-timing equivalent.

Code Examples

<form.Field
  name="confirm_password"
  validators={{
    onChangeListenTo: ['password'],
    onChange: ({ value, fieldApi }) => {
      if (value !== fieldApi.form.getFieldValue('password')) return 'Passwords do not match'
      return undefined
    },
  }}
>
  {(field) => (
    <input value={field.state.value} onChange={(e) => field.handleChange(e.target.value)} />
  )}
</form.Field>
  • What it demonstrates: confirm_password re-validates the moment password changes, not just when confirm_password itself is edited.

Key Takeaways

  1. If a cross-field check only fires on the "wrong" field's own edits and looks stale after editing its counterpart, you're almost certainly missing onChangeListenTo/onBlurListenTo.
  2. fieldApi.form.getFieldValue(...) is the read side of this pattern — it pulls a live value from anywhere else in the form, not just listened-to fields.
  3. This is field-scoped cross-field validation; for validation that inherently spans the whole form (not just two fields), a form-level validator (ch008) is usually a better fit.

Connects To

  • Ch008 Form Validation: the base validator-timing model this extends.
  • Ch026 Field & Form API Classes: getFieldValue/setFieldValue on FormApi.