htmlinputnumbersvalidating

How to make HTML input tag only accept numerical values?


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?


Solution

  • 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 purposes, 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-conditio" with this:

    if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
    

    Source: HTML text input allow only numeric input