Introduction
I came across this situation in Angular where I needed to validate a field based on two conditions. For instance in Australia PayID allows you to pay someone using email or their 10 digit phone number which starts with 04.
First Attempt
So naively, you’d think that you can just use the Validators.email
and Validators.pattern
validators like this:
this.payIdAccountForm = this.fb.group({
payIdAccountControl: ['', [Validators.required,Validators.email, Validators.pattern(/^04\d{8}$/)]]
});
Let’s see how this works in the playground below:
You’ll notice that the error message below the input field doesn’t disappear when you enter a valid email and valid phone number.
This is because if you enter a valid email the Validators.email
validator passes but the Validators.pattern
fails.
Lets fix this next.
Second attempt, using a custom validator
So in our second attempt we will create a custom validator that checks if the input is either a valid email or a valid phone number.
Now you’ll notice that if you enter a valid email or a valid Australian mobile number such as 0412345678
the error message disappears.
Summary
This short article shows you how to validate a field based on two conditions in Angular. Where combining multiple validators through the usual dynamic forms approach doesn’t work as expected. This led us to create a custom validator that checks if the input is either a valid email or a valid phone number. Which workds well for Australian PayID use case.