I have a number
input field which I want to validate with Angular2:
<input type="number" class="form-control" name="foo" id="foo"
[min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo">
So far this works fine in Chrome, because Chrome ignores chars as input (doesn't insert them into the input -> input is empty -> required validation triggers, or there is already a number so the min/max validation triggers).
Firefox on the other hand lets the user input chars into the input and here is the problem, if I insert chars, then the required validation triggers and the value of the form control evaluates as null
which results in this:
I want to distinguish between empty values and invalid patterns but the only way I found to achieve this is by making the input type="text"
and using a pattern validator, because the value of the input is null
(if it contains chars) and the pattern validator does not trigger on the input type="number"
.
Is there a way to access the actual value of the field using the Angular2 FormGroup
object (even document.querySelector('#foo').value
evaluates to null
although the input contains 42bar
)?
Or is there a way to check if the input field contains chars?
Or is there no other way than using input type="text"
?
If you type something into a "number" input that's not a number, the value will be null
. That's the way it's supposed to work.
You can check the .validity.valid
flag to see whether the field has a valid value in it; an empty value is considered valid for number fields.
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