Search code examples
angulartypescriptangular-reactive-formsangular2-form-validation

Is it possible to pass dynamic values to a custom form validator in Angular 6?


basically, i have some form inputs whose validations are dependent on each other (i.e. if you're putting in a time range, the "from" time must be smaller than the "to" time) but i'm not exactly sure how to go about this.

Here is my form group:

this.form = this.fb.group({
  fromTime: ["", [Validators.required, CustomValidator.myValidationFunction(this.form.get("toTime").value)]],
  toTime: ["", [Validators.required]]
});

And here is my validator so far:

static myValidationFunction(testing) {
    const toTime = testing; // only comes here 1 time
    return control => {
      return toTime /*this value never changes*/  ? null : { test: {} };
    };
  }

but it seems as though the value x or toTime is only set the first time when the validator is created. is there a way to pass dynamic inputs to a custom validator?

I'm fairly new to angular, but have read the docs on custom form validation but can't seem to find my answer


Solution

  • static TimeValidator(formGroup) {
        const fromTime = formGroup.controls.fromTime;
        const toTime = formGroup.controls.toTime;
    
        if (fromTime.value && toTime.value) {
            if (toTime.value <= fromTime.value) {
                return {time: true};
            }
    
        }
        return null;
    }
    
    ngOnInit(): void {
        this.form = new FormGroup({
            fromTime: new FormControl('', Validators.required),
            toTime: new FormControl('', Validators.required)
        }, AppComponent.TimeValidator);
    
        this.form.controls.fromTime.setValue(2);
        this.form.controls.toTime.setValue(1);
    }
    

    and in html you can check by:

    {{form.hasError('time')}}
    

    Feel free to ask if you have some questions.