angularvalidationangular5

Angular 5: Validate multiple input fields by sum up values


I would like to validate multiple number input fields by sum up their values and create a custom Validator for Angular.

Every Input looks like this:

<input type="number" min="0" max="10">

There are multiple number inputs and everyone can have a value between 0 and 10, but the sum of all fields must be less or equal 10.

I have a function that returns true if the sum of all input fields is less or equal 10. But how I achieve this with a custom Angular Validator? So that the error message appear instantly.


Solution

  • Like mentioned set validation on the group itself, so do for example:

    this.myForm = fb.group({
      field1: [null],
      field2: [null]
      // more fields 
    }, {validator: this.myValidator})
    

    Then in your validator iterate the formcontrols in your group, sum up and return error or null based on valid or not:

    myValidator(group: FormGroup) {
      let sum = 0;
      for(let a in group.controls) {
        sum += group.get([a]).value;
      }
      return sum > 10 ? { notValid: true} : null
    }
    

    and in template you can display error with:

    *ngIf="myForm.hasError('notValid')"
    

    StackBlitz