I have two input fields: email and phone, if user enters input in email then phone input is not required and vice versa. Atleast one of the fields is required at a time. I have model driven form and I am trying to write a custom validator function for this. So far I have got:
In my validator.ts
:
import { FormGroup, FormControl } from '@angular/forms';
export function requiredOptional(emailVal: string, phoneVal: string) {
return (group: FormGroup): {[key: string]: any} => {
let email = group.controls[emailVal];
let phone = group.controls[phoneVal];
if (!email.value|| !phone.value) {
return {
isRequired: true
};
}
}
}
In my testForm.component.ts
:
export class TestFormComponent{
testForm: FormGroup;
constructor(public fb: FormBuilder) {
this.testForm= fb.group({
email: ['', emailValidator],
phone: ['', phoneValidator],
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
}, {validator: matchingPasswords('password', 'confirmPassword')},
{validator: requiredOptional('email', 'phone')}
)
}
onSubmit(value: Object): void {
console.log(value);
}
}
and in my testForm.component.html
:
<form [formGroup]="testForm" novalidate (ngSubmit)="testForm.valid && onSubmit(testForm.value)">
.......
<input type="email" placeholder="Email*" formControlName="email">
<div class="form-text error" *ngIf="testForm.controls.email.touched">
<div *ngIf="testForm.hasError('isRequired')">Email or Phone is required.</div>
<div *ngIf="testForm.controls.email.hasError('invalidEmail')">Email is invalid.</div>
</div>
.......
<input type="text" placeholder="Mobile Number*" formControlName="phone">
<div class="form-text error" *ngIf="testForm.controls.phone.touched">
<div *ngIf="testForm.hasError('isRequired')">Email or Phone is required.</div>
<div *ngIf="testForm.controls.phone.hasError('invalidPhone')">Phone is invalid.</div>
</div>
.......
<button [disabled]="!testForm.valid" type="submit" class="btn btn-primary pull-right">Sign up</button>
</form>
But this is not working, I am getting error in testForm.component.ts: Supplied parameters do not match any signature of call targets
You can define multiple validating functions by composing like following:
export class TestFormComponent{
testForm: FormGroup;
constructor(public fb: FormBuilder) {
this.testForm= fb.group({
email: ['', emailValidator],
phone: ['', phoneValidator],
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
}, {validator: Validators.compose([matchingPasswords('password', 'confirmPassword'), requiredOptional('email', 'phone')]})
}
onSubmit(value: Object): void {
console.log(value);
}
}
Focus on following change:
{validator: Validators.compose([matchingPasswords('password', 'confirmPassword'), requiredOptional('email', 'phone')]}
Instead of setting matchingPasswords validator, we can set array of validating functions by using Validators.compose