1

I have a reactive form that has very interrelated validations. I created a class that have all the functions for cross field validation, but if I try to set it using Validators.validator it does not trigger the functions. If I just used {validator: MyValidatorClass.myCrossFieldValidator1} this will work on that function, but I have more validators that I need to apply and its not good solution starting creating sub form Groups.

My code looks like this code but with other names

class MyValidatorClass {
  static myCrossFieldValidator1 ...
  static myCrossFieldValidator2 ...
  static myCrossFieldValidator2 ...
}

and the form:

 this.myForm = this.formBuilder.group({
      field1: ['', [Validators.required, Validators.min(0), Validators.maxLength(2)]],  // Done
      field2: ['', [Validators.required, Validators.min(0)]],
      field3: ['', [Validators.required]],
      ...},
     { validator: MyValidatorClass .myCrossFieldValidator1 } // This works but only for one function myCrossFieldValidator1 and is not what I need
     // I have tried with 
     validators & Validators: [MyValidatorClass .myCrossFieldValidator1 
                              ,MyValidatorClass .myCrossFieldValidator12
                              ,MyValidatorClass .myCrossFieldValidator3] 

// But this does not work );

Other solutions around here recommend to declare sub groups or apply the function to a fields but what I am looking is to apply multiple custom cross field validators to my group. Not sure what is wrong or if is a limitation of the technology. Angular in its example only shows the easy case of one validator function https://angular.io/guide/form-validation#cross-field-validation

4

2 回答 2

2

validator: can be a single validator function, or an array of validator functions

     this.myForm = this.formBuilder.group({...},
         { validator: [ MyValidatorClass.myCrossFieldValidator1 , 
                        MyValidatorClass.myCrossFieldValidator12 ,
                        MyValidatorClass.myCrossFieldValidator3
                      ] 
});

FormBuilder#group

于 2018-08-01T22:46:01.623 回答
0

You can use Validators.compose like this:

{ validator: Validators.compose([
          MyValidatorClass.myCrossFieldValidator1, 
          MyValidatorClass.myCrossFieldValidator2
])} 
于 2018-08-01T22:29:04.767 回答