Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
54  
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! – Bennett McElwee Jan 24 '11 at 21:09
53  
@JuliusA - you always always need server-side validation anyway. – Stephen P Nov 23 '11 at 1:57
27  
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input> – Droogans Jan 20 '13 at 20:13
12  
@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. – Alejandro Pérez Nov 5 '13 at 9:54
1  
If you are okay with Plugin, use NumericInput. Demo: jsfiddle.net/152sumxu/2 More details here stackoverflow.com/a/27561763/82961 – Faiz Dec 19 '14 at 7:53

50 Answers 50

You can attach to the key down event and then filter keys according to what you need, for example:

<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);"  type="text">

And the actual javascript handler would be:

function validateNUM(e,field)
{
    var key = getKeyEvent(e)
    if (specialKey(key)) return true;
    if ((key >= 48 && key <= 57) || (key == 46)){ 
        if (key != 46)
            return true;
        else{  
            if (field.value.search(/\./) == -1 && field.value.length > 0) 
                return true;
            else 
                return false;
        }       
    }

function getKeyEvent(e){
    var keynum
    var keychar
    var numcheck
    if(window.event) // IE
        keynum = e.keyCode
    else if(e.which) // Netscape/Firefox/Opera
        keynum = e.which
    return keynum;
}
share|improve this answer
    
Error: ReferenceError: specialKey is not defined – Anant Dabhi Sep 8 '12 at 7:19
    
its not working in my FF browser – Anant Dabhi Sep 8 '12 at 11:03

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);
});
share|improve this answer
    
This is the best (but large) way to do it, don't block usefull things ! – Korri Feb 22 '13 at 22:04
    
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... – Korri Feb 22 '13 at 22:22

This removes any bad character instantly, allows only 1 dot, is short and allows backspace etc.

$('.numberInput').keyup(function () {
    s=$(this).val();
    if (!/^\d*\.?\d*$/.test(s)) $(this).val(s.substr(0,s.length-1));
});
share|improve this answer

Code bellow will also check for PASTE event.
Uncomment "ruleSetArr_4" and add(concate) to "ruleSetArr" to allow FLOAT numbers.
Easy copy/paste function. Call it with your input element in parameter.
Example: inputIntTypeOnly($('input[name="inputName"]'))

function inputIntTypeOnly(elm){
    elm.on("keydown",function(event){
        var e = event || window.event,
            key = e.keyCode || e.which,
            ruleSetArr_1 = [8,9,46], // backspace,tab,delete
            ruleSetArr_2 = [48,49,50,51,52,53,54,55,56,57],	// top keyboard num keys
            ruleSetArr_3 = [96,97,98,99,100,101,102,103,104,105], // side keyboard num keys
            ruleSetArr_4 = [17,67,86],	// Ctrl & V
          //ruleSetArr_5 = [110,189,190], add this to ruleSetArr to allow float values
            ruleSetArr = ruleSetArr_1.concat(ruleSetArr_2,ruleSetArr_3,ruleSetArr_4);	// merge arrays of keys
		
            if(ruleSetArr.indexOf() !== "undefined"){	// check if browser supports indexOf() : IE8 and earlier
                var retRes = ruleSetArr.indexOf(key);
            } else { 
                var retRes = $.inArray(key,ruleSetArr);
            };
            if(retRes == -1){	// if returned key not found in array, return false
                return false;
            } else if(key == 67 || key == 86){	// account for paste events
                event.stopPropagation();
            };

    }).on('paste',function(event){
        var $thisObj = $(this),
            origVal = $thisObj.val(),	// orig value
            newVal = event.originalEvent.clipboardData.getData('Text');	// paste clipboard value
        if(newVal.replace(/\D+/g, '') == ""){	// if paste value is not a number, insert orig value and ret false
            $thisObj.val(origVal);
            return false;
        } else {
            $thisObj.val(newVal.replace(/\D+/g, ''));
            return false;
        };
		
    });
};

var inptElm = $('input[name="inputName"]');

inputIntTypeOnly(inptElm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="inputName" value="1">

share|improve this answer

You may try using the '''onkeydown''' event and cancel the event (event.preventDefault or something like that) when it's not one of the allowed keys.

share|improve this answer

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

share|improve this answer

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:

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) {
        //Exicute Code
    }
}
share|improve this answer

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();
   }
}
share|improve this answer
function digitsOnly(obj) {
   obj.value = obj.value.replace(/\D/g, "");
}

and in the element

<input type="text" onkeyup="digitsOnly(this);" />
share|improve this answer

Yes, HTML5 does. Try this code (w3school):

<!DOCTYPE html>
<html>
<body>

<form action="">
  Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5" />
  <input type="submit" />
</form>

</body>
</html>
share|improve this answer

I use the jquery.inputmask.js library you can download from NUGET. More specifically I use jquery.inputmask.regex.extensions.js that comes with it. I give the input element a class, in this case reg;

<input type="number" id="WorkSrqNo" name="WorkSrqNo" maxlength="6" class="reg"/>

and then in javascript I set the mask;

var regexDigitsOnly = "^[0-9]*$";
$('input.reg').inputmask('Regex', { regex: regexDigitsOnly });

This is for digits only but you can alter regex to accept "." By using this it is impossible to enter characters that are not digits. It is useful to have these inputmask libraries for general formatting.

share|improve this answer
    
Couldn't make this work. Can you show a demo? – Faiz Dec 19 '14 at 6:06

If you are okay with using Plugins, here is one I tested. Works well except for paste.

Numeric Input

Here is a Demo http://jsfiddle.net/152sumxu/2

Code below (Lib pasted in-line) Demo of the plug-in Any Number

<script type="text/javascript">
//  Author: Joshua De Leon - File: numericInput.js - Description: Allows only numeric input in an element. - If you happen upon this code, enjoy it, learn from it, and if possible please credit me: www.transtatic.com
(function(b){var c={allowFloat:false,allowNegative:false};b.fn.numericInput=function(e){var f=b.extend({},c,e);var d=f.allowFloat;var g=f.allowNegative;this.keypress(function(j){var i=j.which;var h=b(this).val();if(i>0&&(i<48||i>57)){if(d==true&&i==46){if(g==true&&a(this)==0&&h.charAt(0)=="-"){return false}if(h.match(/[.]/)){return false}}else{if(g==true&&i==45){if(h.charAt(0)=="-"){return false}if(a(this)!=0){return false}}else{if(i==8){return true}else{return false}}}}else{if(i>0&&(i>=48&&i<=57)){if(g==true&&h.charAt(0)=="-"&&a(this)==0){return false}}}});return this};function a(d){if(d.selectionStart){return d.selectionStart}else{if(document.selection){d.focus();var f=document.selection.createRange();if(f==null){return 0}var e=d.createTextRange(),g=e.duplicate();e.moveToBookmark(f.getBookmark());g.setEndPoint("EndToStart",e);return g.text.length}}return 0}}(jQuery));

$(function() {
   $("#anyNumber").numericInput({ allowFloat: true, allowNegative: true });
});
</script>
share|improve this answer
<script>
function onlyNumber(id){ 
    var DataVal = document.getElementById(id).value;
    document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
}
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">

And if you wanna update value after press key, you can change onChange for onKeypress, onKeyDown or onKeyup. But event onKeypress don't running in any browsers.

share|improve this answer
    
This form is native from Javascript + Regular Expression – Rogerio de Moraes Dec 22 '14 at 18:50

For those of you that like one-liners.

string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

I use this code on an input type="text", and with Angularjs to activate on keypress, but you can use jquery if like. Just put this code into a function that activates on keypress someway.

Only allows digits, digits + decimal, digits + decimal + digits.

CODE

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";

testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";

testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";

testFour = "622632463.23464236326324363"
=> "622632463.23";

This was built for US currency, but can be changed to allow more than two decimals past first decimal place as in the following...

CHANGED CODE

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');

testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";

:)

share|improve this answer

I was looking for a way to block an input of numbers, then, as I did not find it in answers, this code worked fine for me.

I just need to input It in the onkeypress event.

If you need just to block an input of numbers, I believe this will work fine.

onkeypress="if(event.which &lt; 48 || event.which &gt; 57 ) if(event.which != 8) if(e.keyCode != 9) return false;"
share|improve this answer

I might have another (simple) workaround for this ..

Since String.fromCharCode(key) returns weird things upon azerty keyboard ( numerical keypad returns code as g for 1, and 1 for & caracter ..

I've realized catching the final value on keyup within the input to reset it to an arbitrary value is a simpler, lightweight & bugproof method ( could also be done via some regex ... to keep decimals and so on ... don't have to filter other ctrl, home, del, enter events anymore .. )

Usage with jq :

<input class='pn'>
<script>
function pn(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}
jQuery('.pn').keyup(function(){pn(this);});
</script>

Onkeyup attribute :

<input onkeyup='positiveNumericInput(this)'>
<script>function positiveNumericInput(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}</script>
share|improve this answer

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.

share|improve this answer

in html 5 ;
write html attribute " numeric-only " Like this : <input type="text" name="XXX" id="XXX" ng-model="XX.YY" disabled **numeric-only** maxlength="12"/>

share|improve this answer

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);"
share|improve this answer

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.

share|improve this answer

protected by Community Jun 17 '14 at 15:44

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.