0

I am developing a User Form.

I am summarizing my issue, if the user ticked on medical policy checkbox then user have to fill the medical policy detail.

user form group code below:

let userForm = this.myFormBuilder.group({
  userName: ['',Validators.required],
  password: ['',Validators.required],
  isMedicalPolicy: [false],
  medicalPolicyInfo: this.myFormBuilder.group({
    policyNumber: ['',Validator.maxLength(10)], // how to apply conditional required validation here, 
      if is isMedicalPolicy value is true.
  });
});

Please help on this.

1
  • You'll need to observe changes on the isMedicalPolicy field value and then alter the validation of the other fields. Commented Oct 14, 2018 at 16:52

2 Answers 2

2

You can watch for changes to individual form control values, then alter the validation of other controls based on the value.

Example:

const isMedicalPolicyControl = this.userForm.get('isMedicalPolicy');
const policyNumberControl = this.userForm.get('medicalPolicyInfo.policyNumber');

this.subscription = isMedicalPolicyControl.valueChanges.subscribe(value => {

  if (value) {
    policyNumberControl.setValidators([
      Validators.required,
      Validator.maxLength(10)
    ]);
  }
  else {
    policyNumberControl.setValue('');
    policyNumberControl.setValidators(null);
  }

  policyNumberControl.updateValueAndValidity();

});

You'll want to unsubscribe from the valueChanges observable when your component is destroyed.

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

3 Comments

Thanks, Sorry, If forgot to add maxLength validator on policyNumber field. As per the code, if I set the validator null then my maxlength validation will not work. then how do I a manage or I need to add maxLength validator every time if value is true.
No worries. I've updated the sample code. Since your validators only apply if the isMedicalPolicy control has a value of true, you can just assign/de-assign them when the value changes.
Calling policyNumberControl.updateValueAndValidity() inside the function isMedicalPolicyControl.valueChanges.subscribe is causing an infinite loop
0

you can also simply use ternary operators like:

 medicalPolicyInfo: this.myFormBuilder.group({
    policyNumber: ['', isMedicalPolicy ? [ Validator.maxLength(10), Validators.required]:[]]
     
  });

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.