Emanuel Weinsjö
Emanuel Weinsjö

Reputation: 491

Angular 2 combined form validation

I wonder how I can make an combined validation in Angular2 with OR statements in an Control Group. For example i have three input fields and i want to make 1 required and the other two required with OR like. [Input name] = Required, ([Input email] OR [Input phone]) = Required.

this.userForm = this._formBuilder.group({
'name': ['', Validators.required],
'email': ['', Validators.compose([Validators.required, ValidationService.emailValidator]),
 'phone': ['', Validators.required]]

});

Upvotes: 1

Views: 796

Answers (1)

Michael Kang
Michael Kang

Reputation: 52867

The group method takes a second parameter where you can define a custom validation function. This is useful in scenarios where the validation rule depends on the state of one or more other fields.

this.userForm = this._formBuilder.group({
'name': ['', Validators.required],
'email': ['', Validators.compose([Validators.required, ValidationService.emailValidator]),
 'phone': ['', Validators.required]

}, { validator: this.oneRequired('email', 'phone') });

oneRequired(first:string, second:string) {
    return (group: ControlGroup) => {
        var control1 = group.controls[first];
        var control2 = group.controls[second];
        var a = Validators.required(control1) || { required: false };
        var b = Validators.required(control2) || { required: false };
        if (a['required'] && b['required']) {
            control1.setErrors({ oneRequired: true });
            control2.setErrors({ oneRequired: true });
        }
        else {
            control1.setErrors(null);
            control2.setErrors(null);
        }

    };

}

Upvotes: 2

Related Questions