Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input type="number" contains null rather than character

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:

required validation triggers, but input is not empty

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 (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"?

like image 768
Tobias Helbich Avatar asked Oct 18 '25 12:10

Tobias Helbich


1 Answers

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.

like image 158
Pointy Avatar answered Oct 21 '25 00:10

Pointy