Reputation: 758
I have created a student form that has 4 to 5 fields. For the contact number, I have 2 fields, country code and phone number. I want to throw an error if the user only inputs one of the two fields ie country code is entered but the phone number isn't or vice-versa. However, if both fields are left empty, then it's valid as both are non-mandatory fields. I don't know how I can achieve this. Please help. Thanks in advance.
Here is my template:
<mat-form-field >
<input matInput type="number" formControlName="countryCode" placeholder="Country Code(+)" name="countryCode" class="form-control" id="countryCode">
</mat-form-field>
<mat-form-field >
<input matInput type="number" formControlName="phnNumber" placeholder="Phone Number" name="phnNumber" class="form-control" id="phnNumber">
</mat-form-field>
My Form group:
this.addForm = this.formBuilder.group({
studentName: ['', Validators.required],
phnNumber: new FormControl(''),
countryCode: new FormControl(''),
});
Upvotes: 2
Views: 4851
Reputation: 3571
You can create a custom validator which you place on the FormGroup
as a whole rather than the individual controls. Your call to FormBuilder
becomes:
this.addForm = this.formBuilder.group({
studentName: ['', Validators.required],
phnNumber: new FormControl(''),
countryCode: new FormControl(''),
}, { validators: myFormValidator });
And you create a Validator (either in the same file or elsewhere and export):
export const myFormValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const phnNumber = control.get('phnNumber').value;
const countryCode = control.get('countryCode').value;
if (phnNumber && !countryCode || countryCode && !phnNumber) {
return { 'phoneNumberError': true };
} else {
return null;
}
};
That way the custom Validator grabs what it needs from the whole group as opposed to needing to validate controls individually.
Upvotes: 5