Reputation: 963
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.
Upvotes: 0
Views: 3456
Reputation: 505
you can also simply use ternary operators like:
medicalPolicyInfo: this.myFormBuilder.group({
policyNumber: ['', isMedicalPolicy ? [ Validator.maxLength(10), Validators.required]:[]]
});
Upvotes: 0
Reputation: 34553
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.
Upvotes: 2