0
votes

I'm quite familiar with Angular 1.6, just starting to learn Angular 5 and looking at reactive forms so apologies if this is a bit of a newbie question. Our applications have lots of complex validation rules and I can see how in most cases they would be easier to implement with reactive forms. I have some scenario which seems a lot harder, specifically when the input to a validator is the value from another control. Here are two obvious examples:

  • "From" and "to" date fields, where the "to" field must be a later date than the "from" field
  • "Confirm password" field must have the same value as the "password" field.

In Angular 1 land, I would have done something like this:

<input ng-model="vm.from" />
<input ng-model="vm.to" must-be-later-than="vm.from" />

<input ng-model="vm.password" />
<input ng-model="vm.confirmPassword" must-be-identical="vm.password" />

I'd have written custom validator directives for mustBeLaterThan and mustBeIdentical, but I'd have got automatic binding between the fields and the directives would only need to be written once.

In Angular 2/4/5 reactive forms, it seems like I would create validator factory function, but I'm not clear on what I would pass into it as parameters other than the related FormControl, which seems dirty. I could obviously observe changes in one field and repeatedly destroy and recreate validators in the other, but that seems inefficient and convoluted. Is there a better convention that gets used in scenarios like this?

1

1 Answers

0
votes

I discovered the convention (couldn't find it the way I was Googling it because of my assumptions about the solution). You put both fields in a FormGroup and add a validator to the group.