Search code examples
angularangular2-forms

Custom validation for positive numbers


I was trying to find the information, if there are any built-in validators, that check if the input is a positive number?

I was trying to build the following:

static nonZero(control:Control) {
    if (Number(control.value) < 0) {
        control.setErrors({nonZero: true})
    } else {
    control.setErrors(null)
    }
}

However, I didn't know how to use it in my form builder:

this.form = _formBuilder.group({
            field:['', Validators.required]})

What am I doing wrong?


Solution

  • You can configure it this way by leveraging the Validators.compose method:

    this.form = _formBuilder.group({
            field:['', Validators.compose([
                         Validators.required, nonZero ])
            ]});
    

    This allows you to define your two synchronous validators for the field.

    Edit

    I would implement the validator this way:

    static nonZero(control:Control):{ [key: string]: any; } {
      if (Number(control.value) < 0) {
        return {nonZero: true};
      } else {
        return null;
      }
    }