Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force only numbers in a input, without Javascript?

Tags:

html

text

input

CodePen: http://codepen.io/leongaban/pen/hbHsk

I've found multiple answers to this question on stack here and here

However they all suggest the same fix, using type="number" or type="tel"

None of these are working in my codepen or project :(

enter image description here

Do you see what I'm missing?

like image 933
Leon Gaban Avatar asked Aug 01 '13 16:08

Leon Gaban


People also ask

How do I force input fields into numbers only?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I put only numbers in HTML?

The <input type="number"> defines a field for entering a number. Use the following attributes to specify restrictions: max - specifies the maximum value allowed. min - specifies the minimum value allowed.

How do I limit text input to numbers?

To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.


1 Answers

Firstly, what browsers are you using? Not all browsers support the HTML5 input types, so if you need to support users who might use old browsers then you can't rely on the HTML5 input types working for all users.

Secondly the HTML5 input validation types aren't intended to do anything to stop you entering invalid values; they merely do validation on the input once it's entered. You as the developer are supposed to handle this by using CSS or JS to determine whether the field input is invalid, and flag it to the user as appropriate.

If you actually want to prevent non-digit characters from ever getting into the field, then the answer is yes, you need to use Javascript (best option is to trap it in a keyUp event).

You should also be careful to ensure that any validation you do on the client is also replicated on the server, as any client-side validation (whether via the HTML5 input fields or via your own custom javascript) can be bypassed by a malicious user.

like image 82
Spudley Avatar answered Oct 04 '22 14:10

Spudley