How to make HTML input tag only accept numerical values?
Solution 1
HTML 5
You can use HTML5 input type number to restrict only number entries:
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.
JavaScript
Update: There is a new and very simple solution for this:
It allows you to use any kind of input filter on a text
<input>
, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.
See this answer or try it yourself on JSFiddle.
For general purpose, you can have JS validation as below:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
If you want to allow decimals replace the "if condition" with this:
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
Source: HTML text input allow only numeric input
JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/
Solution 2
You can also use the pattern attribute in html5:
<input type="text" name="name" pattern="[0-9]" title="Title" />
Although, if your doctype isn't html
then I think you'll need to use some javascript/jquery.
Solution 3
Quick and Easy Code
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />
This will permit usage of numbers and backspace only.
If you need decimal part too, use this code fragment
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />
Solution 4
Please try this code along with the input field itself
<input type="text" name="price" id="price_per_ticket" class="calculator-input" onkeypress="return event.charCode >= 48 && event.charCode <= 57"></div>
it will work fine.
Solution 5
You can use an <input type="number" />
. This will only allow numbers to be entered into othe input box.
Example: http://jsfiddle.net/SPqY3/
Please note that the input type="number"
tag is only supported in newer browsers.
For firefox, you can validate the input by using javascript:
Update 2018-03-12: Browser support is much better now it's supported by the following:
- Chrome 6+
- Firefox 29+
- Opera 10.1+
- Safari 5+
- Edge
- (Internet Explorer 10+)
Related videos on Youtube
chtenb
Updated on February 27, 2022Comments
-
chtenb over 2 years
I need to make sure that a certain
<input>
field only takes numbers as value. The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.Is there a neat way to achieve this?
-
alexblum over 11 years
-
Maheshkumar over 11 yearsTake a look at this [link][1], which has enough info. [1]: stackoverflow.com/questions/469357/…
-
chtenb almost 11 yearsThis one may also come in handy: stackoverflow.com/questions/995183/…
-
-
chtenb over 11 yearsAlthough firefox gives the input box a red border when non-numbers are typed, in both firefox and chrome, you are able to type non-number characters in the input box.
-
chtenb over 11 yearsIt appears to work very nicely in chrome, but not in firefox.
-
martincarlin87 over 11 yearswhat doctype are you using on your page?
-
chtenb over 11 yearsYep, this works for me in both firefox and chrome. Weird that js is necessary for such a simple thing.
-
starbeamrainbowlabs over 11 yearsAh. That is because firefox does not support input type=number. Alternatively, you could use some javascript to validate the input as the user inputs the text. Answer updated.
-
martincarlin87 over 11 yearsok, maybe it's not supported in the browser versions you have? Not 100% sure but to be honest I'd use some js to validate aswell, I wouldn't rely purely on html5 at the moment
-
chtenb over 11 yearsYeah, agreed. I hoped there would be some well-supported html property, but the javascript in the accepted answer works very neat.
-
Pankit Kapadia over 11 years@Chiel92 - Just to inform it is not necessary. you can do so by server side scripting languages
php
& others. If browser has javascript disabled this won't work ! and you may enter any value fromfirebug
or any other developer tools. -
chtenb over 11 yearsI'm very aware of that. Though it's for a tablet app, I will do serverside validation anyway. But the value of the input influences other UI elements, so it needs to be done clientside as well.
-
Ben about 11 yearsDoesn't work in chrome 30. I have no trouble at all typing letters into your "number" input in the fiddle. Hmmm...
-
syed shah over 10 yearsWhat if someone want to enter float values like 8.9 ?
-
Neil over 10 yearsfor a more robust solution, also consider copy and paste can add letters to this example!
-
Akshay about 10 yearsThe jscript on jsfiddle.net/VmtF5, will also not work. Even if 1 digit is at the start of character, the validation fails. Try it yourself on jsfiddle
-
starbeamrainbowlabs about 10 years@aarn It works for me (see i.imgur.com/AWdmEov.png ), what browser are you using?
-
Akshay about 10 years@starbeamrainbowlabs I am using firefox. Also, enter 6abc, it will not show you the error
-
starbeamrainbowlabs about 10 years@aarn I see what you mean now. That happens beause the javascript used to detect whether the number is valid or not uses
parseFloat()
, which allows extra chracters after the number, for example123kg
. If you wanted to only have the numbers, you might want something like this: jsfiddle.net/b72Qr (from stackoverflow.com/questions/1779013/…) -
peiman F. almost 10 yearsOops!! first line must changed to :
var charCode = (evt.which) ? evt.which : evt.keyCode;
-
QMaster almost 10 years+1 and thanks to @Viral, I seen it and i tried to enhance this way with my knowledge and search results, so I wrote another with min and max range. You could see in: stackoverflow.com/questions/2013229/… Please tell me if you have any additional idea.
-
Muddasir Abbas over 9 yearsHi, any one tell me how to set condition that enter value should be number and also greater than or equal to 20. Thanks in advanced.
-
user3591637 over 9 yearshow would you add ability to put input like .5 or .3?
-
Fredrick Gauss over 9 yearsThen you have to consider first and second characters (
0.43
or.43
) that could be done with checking the value of current input plus pressed key. This would be ugly in one-line code, I recommend to use a function for this. To test integer or float, check here. -
My1 about 8 yearsthe the property lets you enter numbers but not submit the form.
-
Chris Sim over 7 yearsWhen u paste a value containing text, it allows it
-
Chris Sim over 7 yearsyou can't delete a number entered by mistake
-
LewisJWright over 7 yearsWhy would the shift key return true? I know its not necessarily a problem but i'm just curious.
-
Eric Hodonsky over 7 yearsSUBMIT VALIDATION ONLY!
-
Joyston over 6 yearsIt accepts numbers such as 12.12.23. (with more than 1 decimals)
-
Brad Ahrens over 6 yearsThis code works great. Just 1 slight problem. It allows me to type in special characters such as: ãôéè, etc. etc. Any idea how to block those as well?
-
Brad Ahrens over 6 yearsIt allows special characters as well. For example: á, ã, ê, ó, è, etc.
-
JoshG almost 6 yearsWelcome to SO! Unfortunately, this is a 5 1/2 year old question that already has an accepted answer. You might want to browse questions without answers here: stackoverflow.com/unanswered
-
grant sun almost 6 yearsif you use ctrl + v, it will break.
-
6by3 almost 6 yearshow to delete backspace then?
-
Nirmal almost 5 yearsThat's why I love regex. Thanks, man, you really saved my day
-
Normajean about 4 yearscheck out my answer
-
Allan over 3 yearsIs there a way to limit the number of decimals, as to use it for prices?
-
abhijithvijayan over 3 yearsit returns a boolean value so I guess you can add another check that takes the current value and checks if the length is under what you specified.
-
Jim Speaker over 3 yearsGiven how I'm doing validation in this particular case this solution works really well. +1
-
Armen Michaeli about 3 yearsUpvoted for the first paragraph and downvoted for the rest.
-
Syafiqur__ almost 3 yearsI think this is the simplest way. No need JS, and clean look.
-
Florida over 2 yearsPerfect if you need to add
0
in front of the numbering.01
,02
...010
or009
.