I'm building this form that has a field that's not required, however, in case the user enters their phone number I want to validate it AND make it required. If there is nothing, the Validation required should be removed.
I have this but it doesn't work.
private checkNum( ctrl: FormControl ) {
let valid = false;
if ( ctrl ) {
ctrl.setValidators(Validators.required);
if ( ctrl.value.length ) {
const phoneNumber = this.phoneNumberUtil.parseAndKeepRawInput( ctrl?.value, 'us' );
valid = this.phoneNumberUtil.isValidNumber(phoneNumber);
if (validNumber) {
this.validPhoneNum = this.phoneNumberUtil.format(phoneNumber, PhoneNumberFormat.E164);
return null
}
return { required: 'Phone Invalid' }
}
return { required: 'Phone Invalid' }
} else {
return ctrl.clearValidators();
}
}