1126

Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus '.')?

16
  • 105
    Many solutions here only work when keys are pressed. These will fail if people paste text using the menu, or if they drag and drop text into the text input. I've been bitten by that before. Be careful! Commented Jan 24, 2011 at 21:09
  • 1
    @haemse - Not if you use the mouse to paste. Commented Sep 30, 2011 at 21:33
  • 105
    @JuliusA - you always always need server-side validation anyway. Commented Nov 23, 2011 at 1:57
  • 74
    <input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input> Commented Jan 20, 2013 at 20:13
  • 20
    @Droogans notice that also disables any other key, like TAB to go to the next input or any other shortcut not directly involved with input like cmd+R for refreshing the website if the input is focused. Commented Nov 5, 2013 at 9:54

79 Answers 79

1 2
3
1

For ReactJS:

<input
    onKeyPress={(event) => {
        if (!/[0-9]/.test(event.key)) {
            event.preventDefault();
        }
    }}
/>

Sign up to request clarification or add additional context in comments.

1 Comment

This does not allow input deletion. The user needs to refresh the page to enter a different number.
1

I've used type=tel to be able to limit the number of digits and to allow only digits, I've used the following code:

HTML

<input type="tel" class="form-control number-only" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits"/>

JQuery

$('.number-only').on('input', (e) => {
  e.target.value = e.target.value.replace(/[^\d]/g, '');
});

Comments

0

Thanks guys this really help me!

I found the perfert one really useful for database.

function numonly(root){
    var reet = root.value;    
    var arr1=reet.length;      
    var ruut = reet.charAt(arr1-1);   
        if (reet.length > 0){   
        var regex = /[0-9]|\./;   
            if (!ruut.match(regex)){   
            var reet = reet.slice(0, -1);   
            $(root).val(reet);   
            }   
        }  
 }

Then add the eventhandler:

onkeyup="numonly(this);"

Comments

0

I realize an old post but i thought this could help someone. Recently I had to limit a text box to just 5 decimal places. In my case ALSO the users input had to be less than 0.1

<input type="text" value="" maxlength=7 style="width:50px" id="fmargin" class="formText"  name="textfield" onkeyup="return doCheck('#fmargin',event);">

Here is the doCheck function

function doCheck(id,evt)
{
    var temp=parseFloat($(id).val());

    if (isNaN(temp))
        temp='0.0';
    if (temp==0)
        temp='0.0';

    $(id).val(temp);
}

Here is the same function except to force integer input

function doCheck(id,evt)
{
    var temp=parseInt($(id).val());

    if (isNaN(temp))
        temp='0';

    $(id).val(temp);
}

hope that helps someone

Comments

0

I tweaked it some, but it needs a lot more work to conform to the JavaScript weirding way.

function validateNumber(myEvent,decimal) {
    var e = myEvent || window.event;
    var key = e.keyCode || e.which;

    if (e.shiftKey) {
    } else if (e.altKey) {
    } else if (e.ctrlKey) {
    } else if (key === 48) { // 0
    } else if (key === 49) { // 1
    } else if (key === 50) { // 2
    } else if (key === 51) { // 3
    } else if (key === 52) { // 4
    } else if (key === 53) { // 5
    } else if (key === 54) { // 6
    } else if (key === 55) { // 7
    } else if (key === 56) { // 8
    } else if (key === 57) { // 9

    } else if (key === 96) { // Numeric keypad 0
    } else if (key === 97) { // Numeric keypad 1
    } else if (key === 98) { // Numeric keypad 2
    } else if (key === 99) { // Numeric keypad 3
    } else if (key === 100) { // Numeric keypad 4
    } else if (key === 101) { // Numeric keypad 5
    } else if (key === 102) { // Numeric keypad 6
    } else if (key === 103) { // Numeric keypad 7
    } else if (key === 104) { // Numeric keypad 8
    } else if (key === 105) { // Numeric keypad 9

    } else if (key === 8) { // Backspace
    } else if (key === 9) { // Tab
    } else if (key === 13) { // Enter
    } else if (key === 35) { // Home
    } else if (key === 36) { // End
    } else if (key === 37) { // Left Arrow
    } else if (key === 39) { // Right Arrow
    } else if (key === 190 && decimal) { // decimal
    } else if (key === 110 && decimal) { // period on keypad
    // } else if (key === 188) { // comma
    } else if (key === 109) { // minus
    } else if (key === 46) { // Del
    } else if (key === 45) { // Ins
    } else {
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
    }
}

And then it's called via:

$('input[name=Price]').keydown(function(myEvent) {
    validateNumber(myEvent,true);
});

2 Comments

This is the best (but large) way to do it, don't block usefull things !
Althought, it doesn't work well for me, on my computer, keycode 100 is 'd' key, and my keypad '4' key is 52, I don't think keycode is really reliable...
0

Regular expressions and the match function can work well for this situation. For instance, I used the following to validate 4 input boxes that served as coordinates on a graph. It works reasonably well.

function validateInput() {
   if (jQuery('#x1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#x2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#y1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
       jQuery('#y2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null) {
         alert("A number must be entered for each coordinate, even if that number is 0. Please try again.");
         location.reload();
   }
}

Comments

0

When it comes to fool-proofing UX, one should always try to keep a reference point for the 'user's intelligence'.

While neglecting everything other than numbers, a dot and a hyphen would seem like the perfect choice, you should also consider letting them enter any content, and when they're done, purify the input; if not a valid number, show error. This method would make sure no matter what the user manages to do, the result will always be valid. If the user is naive enough not to understand the warnings and error messages, pressing a button and seeing that nothing happens (as in keycode comparison) will only confuse him/her more.

Also, for forms, validation and error message display are almost a necessity. So, the provisions might already be there. Here's the algorithm:

  1. On losing-focus or form-submission, do following.

    1.1. Read content from the input and apply parseFloat to result

    1.2. If the result is a Non-accessible-Number (NaN), reset the input field and pop-up an error message: "Please enter a valid number: eg. 235 or -654 or 321.526 or -6352.646584".

    1.3. Else, if String(result)!==(content from input), change value of the field to result and show warning message: "The value you entered have been modified. Input must be a valid number: eg. 235 or -654 or 321.526 or -6352.646584". For a field that cannot allow any unconfirmed value, then this condition may be added to step 1.2.

    1.4. Else, do nothing.

This method also gives you the added advantage of performing validations based on minimum value, maximum value, decimal places, etc if necessary. Just have to do these operations on the result after step 1.2.

Disadvantages:

  1. The input will allow the user to enter any value until the focus is lost or the form is submitted. But if the instructions on filling the field were clear enough, in 90% of the cases this might not come up.

  2. If step 1.3 is used to display a warning, it might be overlooked by the user and might result in unintentional input submission. Throwing an error or displaying the warning properly would solve this.

  3. Speed. This might be slower in microseconds than the regex method.

Advantages: Assuming the user have basic knowledge to read and understand,

  1. Highly customizable with options.

  2. Works cross browser and independent of language.

  3. Makes use of already available features in a form to display errors and warnings.

Comments

0

Hope I am not beating a dead horse with an ugly stick here, but I am using this for my website quantity input, it allows only numbers from 1 to 99.

Try it: https://jsfiddle.net/83va5sb9/

      <input min="1" type="text" id="quantity" name="quantity" value="1"
      onKeyUp="numbersonly()">

      <script>
    function numbersonly() {
      var str = document.getElementById("quantity").value
      var newstr = ""
      for (i = 0; i < str.length; i++) {
        for (ii = 1; ii < 10; ii++) {
          if (str.charAt(i).indexOf(ii) > -1) {
            newstr += str.charAt(i)
          }
        }
      }
      if (newstr == "") {
        newstr = 1
      }
      if (parseInt(newstr) > 99) {
        newstr = 99
      }
      document.getElementById("quantity").value = newstr
    }

    </script>

Comments

0

Call this function when ready to validate what ever. I used a textbox here

In my HTML:

<input type="button" value="Check IT!" onclick="check(document.getElementById('inputboxToValidate').value);" />

In my JavaScript code:

function check(num){
    var onlynumbers = true
    for (var i = 0; i < (num.length - 1); i++) {
        if (num.substr(i, 1) != "0" || num.substr(i, 1) != "1" || num.substr(i, 1) != "2" || num.substr(i, 1) != "3" || num.substr(i, 1) != "4" || num.substr(i, 1) != "5" || num.substr(i, 1) != "6" || num.substr(i, 1) != "7" || num.substr(i, 1) != "8" || num.substr(i, 1) != "9") {
            alert("please make sure that only numbers have been entered in the Quantaty box");
            onlynumbers = false
        }
    }
    if (onlynumbers == true) {

        //Execute Code
    }
}

Comments

0

Some of the answers above use outdated content, like the use of which.

To check if the pressed key is a number you use a keyup eventListener to read the value of event.key. Then simply prevent the typing of the character if it's not a number. You can whitelist additional keys. Example, allow the user to navigate backward or forwards in the input field with the arrows, or to hit backspace and delete the typed-in numbers.

validate (event) {
  const isNumber = isFinite(event.key)
  const whitelist = ['Backspace','Delete','ArrowDown','ArrowUp','ArrowRight','ArrowLeft']
  const whitelistKey = whitelist.includes(event.key)

  if (!isNumber && !whitelistKey) {
    event.preventDefault()
  }
}

Comments

0

Here is an Object-Oriented re-implementation of emkey08's JavaScript Wiki answer which uses an EventListener object implementation. (See: MDN web docs EventListener)

In a way, it prevents duplicating anonymous event handler function declarations for each filtered input element, while still allowing it through an optional call-back.

/**
 * Base input {@see Element} {@see EventListener} filter abstract class
 *
 * @implements EventListener
 */
class AbstractInputFilter {

  /**
   * Attach the input filter to the input {@see Element}
   *
   * @param inputElement The input {@see Element} to filter
   * @param isValid - The callback that determines if the input is valid.
   * @throws Error
   */
  constructor(inputElement, isValid = null) {
    // Abstract class
    if (this.constructor === AbstractInputFilter) {
      throw new Error("Object of Abstract Class cannot be created");
    }

    if (typeof isValid === "function") {
      this.isValid = isValid;
    }

    for (const event of ["input", "keydown", "keyup",
        "mousedown", "mouseup", "select", "contextmenu", "drop"]) {
      inputElement.addEventListener(event, this);
    }
  }

  /**
   * Checks the value is valid
   *
   * @callback isValid default call-back that will throw
   * an {Error} if not implemented by extending this 
   * {AbstractInputFilter} class.
   *
   * @param value The value to check
   * @returns {boolean}
   * @throws Error
   */
  isValid(value) {
    throw new Error('must be implemented by callback!');
  }

  /**
   * Handles the {@see event} dispatched by
   * the {@see EventTarget} object from the input {@see Element}
   * to filter its contant while it is being filled.
   *
   * @param event the {@see event} dispatched by
   * the {@see EventTarget} input {@see Element}
   * @override
   */
  handleEvent(event) {
    const inputElement = event.currentTarget;
    if (this.isValid(inputElement.value)) {
      inputElement.oldValue = inputElement.value;
      inputElement.oldSelectionStart = inputElement.selectionStart;
      inputElement.oldSelectionEnd = inputElement.selectionEnd;
    } else if (inputElement.hasOwnProperty("oldValue")) {
      inputElement.value = inputElement.oldValue;
      inputElement.setSelectionRange(
        inputElement.oldSelectionStart, inputElement.oldSelectionEnd);
    } else {
      this.value = "";
    }
  }
}

/**
 * Generic Input element {@see EventListener} filter
 *
 * @extends AbstractInputFilter
 * It needs the {@see AbstractInputFilter~isValid} callback
 * to determine if the input is valid.
 */
class InputFilter extends AbstractInputFilter {}

/**
 * Unsigned Integer Input element {@see EventListener} filter
 * @extends AbstractInputFilter
 */
class UIntInputFilter extends AbstractInputFilter {
  isValid(value) {
    return /^\d*$/.test(value);
  }
}

/**
 * Unsigned Float Input element {@see EventListener} filter
 * @extends AbstractInputFilter
 */
class UFloatInputFilter extends AbstractInputFilter {
  isValid(value) {
    return /^\d*\.?\d*$/.test(value);
  }
}

// Filter with pre-made InputFilters (re-use the filter)
new UIntInputFilter(document.getElementById("UInt"));
new UFloatInputFilter(document.getElementById("UFloat"));

// Filter with custom callback filter anonymous function
new InputFilter(document.getElementById("AlNum"), function(value) {
  return /^\w*$/.test(value);
});
<label>Unsigned integer: </label><input id="UInt"><br/>
<label>Unsigned float: </label><input id="UFloat"><br/>
<label>AlphaNumeric (no special characters): </label><input id="AlNum">

Comments

0

input type="tel" works well on mobile devices, so you want to keep that.

Just use the following code (JQuery):

$("input[type=tel]").keydown(function (event) {
        return (event.which >= 48 && event.which <= 57) || //0 TO 9
        event.which === 8 || event.which == 46; //BACKSPACE/DELETE
    });

And your input will be:

<input type="tel" />

And you can add whatever you like to the input field, id, and dont need to bind any other listeneres.

Comments

0

use this regex /\D*/g

const phoneHandler = (event: React.ChangeEvent<HTMLInputElement>) =>{
setPhone(event.target.value.replaceAll(/\D*/g, ''));};

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
0

function isNumeric(event) {
  const keyCode = event.keyCode || event.which;
  const keyValue = String.fromCharCode(keyCode);

  // Allow numeric keys, backspace, delete, and decimal point
  const numericRegex = /[0-9]|\.|Backspace|Delete/;

  if (!numericRegex.test(keyValue)) {
    event.preventDefault();
    return false;
  }
}
<input type="text" id="numericInput" onkeydown="return isNumeric(event)" />

2 Comments

Delete does not work on FF
backspace doesn't work!
0

Look at this answer, hope you could not find any bug. Only numeric input

$(document).on('keydown','input[name^=qtyInvItem_]',function(event){
   var element = this;
    var val = this.value;
   var decimalAllowed = 2;
   if(positiveNumber(event,element,val,decimalAllowed) === false){return false;};
});


  function positiveNumber(event,element,value,allowedDecimalDigits){
    const selectionStart = element.selectionStart;
    const key = event.key;
    var allowedKeys =  [".","0","1","2","3","4","5","6","7","8","9","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","Backspace","Delete","Tab","PageUp","PageDown"];
    var numberKeys = ["0","1","2","3","4","5","6","7","8","9"];
    // prevent double decimal point
    if(key === "." && value.includes(".")){return false;}; 
     // allow allowedKeys
    if(allowedKeys.includes(key) === false){return false;};
    var decimalsPart = value.split(".");
    let part2 = decimalsPart[1]; // get digits after decimal point
    //allow number increase on left side of decimal point and prevent more digits entry on the right side of decimal point
    if(value.indexOf(".") !== -1 && selectionStart > value.indexOf(".") &&  part2.length === allowedDecimalDigits && numberKeys.includes(key)){
    return false;
   }
}

Comments

-1

I have seen many questions that answer this with javascript, but the best answer is to use the type="number" and remove the spin button with css, most of the reason why this is needed is that the spin button doesn't emit the change event when used.

Solution:

HTML

<input type="number" class="input-class">

CSS

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* Firefox */
input[type=number] {
  -moz-appearance: textfield;
}

Comments

-1

Here's my one-line solution!

$('#input-field').keypress(e => !String.fromCharCode(e.which).match(/\D/g));

1 Comment

this code is not working.
-2

I personally suggest to use the autoNumeric plugin from http://www.decorplanit.com/plugin/ - it supports all different variations like prefix/suffix handling, currency handling, negative value formatting, min, max etc.

Comments

-3

Below function will check for every input char if it is number.

numeric: value => {
    let numset = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
    console.log(numset.has(value.substring(value.length - 1, value.length)));
}

Comments

1 2
3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.