How to make HTML input tag only accept numerical values?

826,917

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" /> 

Input validation tutorial

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:

http://jsfiddle.net/VmtF5/

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+)
Share:
826,917

Related videos on Youtube

chtenb
Author by

chtenb

Updated on February 27, 2022

Comments

  • chtenb
    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?

  • chtenb
    chtenb over 11 years
    Although 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
    chtenb over 11 years
    It appears to work very nicely in chrome, but not in firefox.
  • martincarlin87
    martincarlin87 over 11 years
    what doctype are you using on your page?
  • chtenb
    chtenb over 11 years
    Yep, this works for me in both firefox and chrome. Weird that js is necessary for such a simple thing.
  • starbeamrainbowlabs
    starbeamrainbowlabs over 11 years
    Ah. 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
    martincarlin87 over 11 years
    ok, 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
    chtenb over 11 years
    Yeah, agreed. I hoped there would be some well-supported html property, but the javascript in the accepted answer works very neat.
  • Pankit Kapadia
    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 from firebug or any other developer tools.
  • chtenb
    chtenb over 11 years
    I'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
    Ben about 11 years
    Doesn't work in chrome 30. I have no trouble at all typing letters into your "number" input in the fiddle. Hmmm...
  • syed shah
    syed shah over 10 years
    What if someone want to enter float values like 8.9 ?
  • Neil
    Neil over 10 years
    for a more robust solution, also consider copy and paste can add letters to this example!
  • Akshay
    Akshay about 10 years
    The 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
    starbeamrainbowlabs about 10 years
    @aarn It works for me (see i.imgur.com/AWdmEov.png ), what browser are you using?
  • Akshay
    Akshay about 10 years
    @starbeamrainbowlabs I am using firefox. Also, enter 6abc, it will not show you the error
  • starbeamrainbowlabs
    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 example 123kg. If you wanted to only have the numbers, you might want something like this: jsfiddle.net/b72Qr (from stackoverflow.com/questions/1779013/…)
  • peiman F.
    peiman F. almost 10 years
    Oops!! first line must changed to : var charCode = (evt.which) ? evt.which : evt.keyCode;
  • QMaster
    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
    Muddasir Abbas over 9 years
    Hi, 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
    user3591637 over 9 years
    how would you add ability to put input like .5 or .3?
  • Fredrick Gauss
    Fredrick Gauss over 9 years
    Then 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
    My1 about 8 years
    the the property lets you enter numbers but not submit the form.
  • Chris Sim
    Chris Sim over 7 years
    When u paste a value containing text, it allows it
  • Chris Sim
    Chris Sim over 7 years
    you can't delete a number entered by mistake
  • LewisJWright
    LewisJWright over 7 years
    Why would the shift key return true? I know its not necessarily a problem but i'm just curious.
  • Eric Hodonsky
    Eric Hodonsky over 7 years
    SUBMIT VALIDATION ONLY!
  • Joyston
    Joyston over 6 years
    It accepts numbers such as 12.12.23. (with more than 1 decimals)
  • Brad Ahrens
    Brad Ahrens over 6 years
    This 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
    Brad Ahrens over 6 years
    It allows special characters as well. For example: á, ã, ê, ó, è, etc.
  • JoshG
    JoshG almost 6 years
    Welcome 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
    grant sun almost 6 years
    if you use ctrl + v, it will break.
  • 6by3
    6by3 almost 6 years
    how to delete backspace then?
  • Nirmal
    Nirmal almost 5 years
    That's why I love regex. Thanks, man, you really saved my day
  • Normajean
    Normajean about 4 years
    check out my answer
  • Allan
    Allan over 3 years
    Is there a way to limit the number of decimals, as to use it for prices?
  • abhijithvijayan
    abhijithvijayan over 3 years
    it 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
    Jim Speaker over 3 years
    Given how I'm doing validation in this particular case this solution works really well. +1
  • Armen Michaeli
    Armen Michaeli about 3 years
    Upvoted for the first paragraph and downvoted for the rest.
  • Syafiqur__
    Syafiqur__ almost 3 years
    I think this is the simplest way. No need JS, and clean look.
  • Florida
    Florida over 2 years
    Perfect if you need to add 0 in front of the numbering. 01, 02...010 or 009.