MrRobot
MrRobot

Reputation: 1167

How to validate field only if filled

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();
    }
}

Upvotes: 0

Views: 1227

Answers (1)

Srikar Phani Kumar M
Srikar Phani Kumar M

Reputation: 1384

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
   }

}

Upvotes: 1

Related Questions