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).
Problem
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:
Question
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 (evendocument.querySelector('#foo').value
evaluates tonull
although the input contains42bar
)?Or is there a way to check if the input field contains chars?
Or is there no other way than using
input type="text"
?
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).
Problem
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:
Question
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 (evendocument.querySelector('#foo').value
evaluates tonull
although the input contains42bar
)?Or is there a way to check if the input field contains chars?
Or is there no other way than using
input type="text"
?
1 Answer
Reset to default 7If 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.