Question presented to candidate: "On our registration form, the phone number is required only if the user picks 'contact me by phone', and the confirm-password field must match the password. How do you implement validation where one field's rules depend on another field's value?"
What a strong answer should cover:
- Two different problems: a cross-field rule (confirm must equal password) and a conditional rule (phone required only when contact method is phone).
- Cross-field rules go on the parent FormGroup (
new FormGroup({...}, { validators: matchFields(...) })), because the group re-validates whenever any child changes; the error lives on the group (form.errors). - A validator on the child that peeks at
control.parentgoes stale: it does not re-run when the other field changes. - Conditional rules: subscribe to the driver field's
valueChangesand calladdValidators/removeValidators(orsetValidators), thenupdateValueAndValidity(), which is required or the status stays stale. - Keep a reference to the validator function so
removeValidatorscan find it;Validators.minLength(3)creates a new function every call. - Clean up the subscription (
takeUntilDestroyed), and mention the alternative of a group validator that encodes the condition, and Signal Forms'validatewithvalueOf/applyWhen.
Clarifying questions expected:
- "Should the mismatch error be shown on the confirm field, or as a form-level message?"
- "When the phone becomes optional again, should an already typed number be kept or cleared?"
Code / implementation expected: Yes β a group-level validator plus a validator swapped in response to another control's value.