Reputation: 26
I have question how to valid on two fields simultaneously in Angular FormGroup. I must create custom validation on value return backend I don't have any idea how to create it. Thanks for any idea.
Upvotes: 0
Views: 1630
Reputation: 1129
You need to create AsyncValidator and bind it to the FormGroup, then you will have access to the group fields and can validate two fields in one validation tick. There is some example for you:
group = new FormGroup(
{
a: new FormControl(''),
b: new FormControl(''),
},
{ asyncValidators: customAsyncValidator() }
);
function customAsyncValidator(): AsyncValidatorFn {
return (group: FormGroup) => {
const a = group.get('a').value;
const b = group.get('b').value;
return of('value').pipe(
delay(500),
map((value) => (value === a || value === b ? null : { fields: true }))
);
};
}
Hope this helps. Stackblitz
Upvotes: 1