How to check the control of a reactive form, which depends on the management of another form?

Angular Form Component Class:

export class SpecsFilterFormComponent implements OnInit {

  specFilterForm: FormGroup;
  cameraSizeMin = new FormControl("", [Validators.pattern("\s*|[0-9.]*")]);
  cameraSizeMax = new FormControl("", [Validators.pattern("\s*|[0-9.]*")]);

  constructor(private fb: FormBuilder) {    }

  ngOnInit() {

  this.specFilterForm = this.fb.group({
  cameraSize: this.fb.group(
    {
      cameraSizeMin: this.cameraSizeMin,
      cameraSizeMax: this.cameraSizeMax,
    })
});

this.specFilterForm.valueChanges.debounceTime(500).filter(
  formData => this.specFilterForm.valid)
  .subscribe(
    formData => {
      console.log("do something after validation")
    });
  }
  }

I want to add validation to make sure that cameraSizeMax> = cameraSizeMin, how to apply this check in the control cameraSizeMin and cameraSizeMax.

+4
source share
1 answer

I created a special validator that applies to the full group of forms and then adds an error to the form control:

The following CameraSizeMin settings are invalid.

class CustomValidator {
  static validate(abstractForm: FormGroup): {[key: string]: any} => {
    let cameraSizeMin = abstractForm.get("cameraSizeMin");
    let cameraSizeMax = abstractForm.get("cameraSizeMax");

    //validation logic in condition below
    if (true) {
      cameraSizeMin.setErrors({"customValidation": true});
    }
  }
}

You will register it in the form group:

this.specFilterForm = this.fb.group({
  cameraSize: this.fb.group(
    {
      cameraSizeMin: this.cameraSizeMin,
      cameraSizeMax: this.cameraSizeMax,
    }, {validator: CustomValidator.validate}
  )
});
+2
source

Source: https://habr.com/ru/post/1679976/


All Articles