0

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();
    }
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
MrRobot
  • 1,001
  • 1
  • 14
  • 34
  • The dynamic required validation does not make any sense, remove it. The rest of your custom validation should either fail or pass *if* there is a value present. Otherwise do not execute it and return null; – Igor Apr 26 '21 at 18:49

1 Answers1

1

So in order to change validators for a control, you need to do the following:

// In your case: 

checkNum(ctrl: FormControl) {
   if (ctrl && ctrl.value) {
      ctrl.setValidators(Validators.required);
      ctrl.updateValueAndValidity(); // This line is important

       // Here you can do your functionality to match a regex and validate it   
   } else {
      ctrl.setValidators(null);
      ctrl.updateValueAndValidity(); // this line is important
   }

}

Srikar Phani Kumar M
  • 1,069
  • 1
  • 3
  • 8