8

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.

Javed
  • 5,904
  • 4
  • 46
  • 71
  • can use Validator.compose to include the current validation and the other validation criteria(custom validator). – praveen Jun 23 '17 at 14:06

1 Answers1

5

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}
  )
});
developer033
  • 24,267
  • 8
  • 82
  • 108
rainerhahnekamp
  • 1,087
  • 12
  • 27