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.
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')"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With