Solution: Cross-reference Validation
Explore a possible solution for the previous cross-reference validation exercise.
We'll cover the following
Let us break down the solution into its sub-parts.
The Component
class
The exercise requirements asked us to make all form fields mandatory. For this, we could use the built-in validator, Validators.required
(lines 22–24). Moreover, since we need to validate the value of two different form fields, we assign a custom validator to the FormGroup
property, allowing us to have access to all of the form’s child controls (lines 26–33). Here, both versions for the cross validation are displayed:
Line 28: The
validators: orderValidator
custom validator is the simplest solution. It delegates to the custom validator the responsibility of knowing which form controls are involved. However, this approach has some flaws. If any of the target controls’ keys are renamed, this change must also be reflected in the custom validator. Otherwise, the validation will not work or errors will be thrown. Another drawback is that the custom validator isn’t reusable and since its logic is quite generic—checking the value equality of two fields—it’s very likely the same validator could be used elsewhere in the project.Line 31: We register
equalityValidator(‘email’, ‘emailConfirm’)
. We pass the controls’ keys from outside, letting the validator concentrate only on the validation logic and making it reusable. If we want to use the same validator in another form, we can pass the new keys without the need to change anything.
Get hands-on with 1400+ tech skills courses.