Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a reactive form control that is dependent on another form control? [duplicate]

Angular Form component class is :

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 a validation to make sure that cameraSizeMax >= cameraSizeMin, how to apply this validation in the from control cameraSizeMin and cameraSizeMax.

like image 321
javed Avatar asked Jun 23 '17 13:06

javed


People also ask

How do you validate a Reactive form?

To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class. Then, pass the validator function directly to the FormControl to apply it.

What is cross field validation?

In simple words, making sure our data is correct by using multiple fields to check the validity of another. In fancier terms, this process is called Cross Field Validation. Sanity checking your dataset for data integrity is essential to have accurate analysis and running machine learning models.

What is updateValueAndValidity?

updateValueAndValidity allows you to modify the value of one or more form controls and the flag allows you to specify if you want this to emit the value to valueChanges subscribers.


1 Answers

I have created a custom validator that is applied to the complete formgroup and adds then the error at the form control:

Following sets the cameraSizeMin to 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 register it to the formGroup by:

this.specFilterForm = this.fb.group({
  cameraSize: this.fb.group(
    {
      cameraSizeMin: this.cameraSizeMin,
      cameraSizeMax: this.cameraSizeMax,
    }, {validator: CustomValidator.validate}
  )
});
like image 155
rainerhahnekamp Avatar answered Oct 22 '22 16:10

rainerhahnekamp