0

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.

3
  • You build a Validator for the FormGroup as opposed to for the FormControl. That allows you to check whether both fields are valid before validating the overall FormGroup. Commented May 19, 2022 at 13:30
  • You can use the same validator for each of them. From what your write, I can suggest you use AsyncValidator Commented May 19, 2022 at 13:31
  • I'll add that i must two value for at the same time, to check validation. Commented May 19, 2022 at 13:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.