Home > database >  Form validation - To require only one field OR the other. setErrors(null) not working - Angular 11
Form validation - To require only one field OR the other. setErrors(null) not working - Angular 11

Time:01-14

I have a form that has a couple of fields, but two of them have the following rule: If you fill field 1, you don't have to fill field 2 and vice-versa.

All fields have their own custom validators, however, I am not sure how to do the validator for said field 1 and field 2, since only one of them is required to be filled. I thought of using a select, but the field needs to be filled properly and masked and both fields have different mask rules.

I have the following:

  formNewGroup: FormGroupTypeSafe<NewGroup>;
  // Currently they are all under formNewGroup
  inputFieldDocument: FormControl = new FormControl(); // field 1
  inputOtherFieldDocument: FormControl = new FormControl(); // field 2
  inputResponsibleName: FormControl = new FormControl(); // other fields
  inputResponsibleEmail: FormControl = new FormControl(); // other fields
  inputUserName: FormControl = new FormControl(); // other fields
  inputName: FormControl = new FormControl(); // other fields
  inputActive: FormControl = new FormControl(); // other fields

invalidFieldDocument = false;
invalidOtherFieldDocument = false;
// ... another invalidFields

...

validateThisField() {
    const value = this.inputFieldDocument.value;
    this.invalidFieldDocument = !isValid(value);

    if(!this.invalidFieldDocument) {
      this.formNewGroup.controls.OtherField.markAsTouched()

      if(this.formNewGroup.controls.OtherField.hasError) {
        this.inputOtherField.setErrors(null)
        this.formNewGroup.controls.OtherField.setErrors(null)
        this.formNewGroup.controls.OtherField.updateValueAndValidity()
        console.log (this.formNewGroup.controls.OtherField.status) // SAYS 'INVALID'
      }
    }
 }
...

The "Other Field" has literally a mirror of "Field" but the references are swapped.

I`ve got to setErrors(null) solution by looking at other questions in here and it seems to work for everyone, so I don't know what I am doing wrong here.

CodePudding user response:

You aren't using the proper tool to solve your issue here. You shouldn't do this at the field level but at the form group level.

What you need is a cross-field validator. Here is the documentation for it.

As a general rule, validators can be define at any level of a form control, so either for a formfield, a formgroup a formarray. Validator for a given form control should only depends on that form control no other form control. That's one of the main reason behind the design of FormGroups and FormArray.

  • Related