2016-04-25 67 views
1

我想知道如何在控制組中使用OR語句在Angular2中進行組合驗證。例如,我有三個輸入字段,我想使1需要,其他兩個需要與或。 [輸入名稱] =必需,([輸入電子郵件]或[輸入電話])=必需。Angular 2合併表單驗證

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

});

回答

2

組方法採用第二個參數,您可以在其中定義自定義驗證函數。這在驗證規則依賴於一個或多個其他字段的狀態的情況下很有用。

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); 
     } 

    }; 

}