Contact   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

Restricting Input in HTML Textboxes to Numeric Values


Ok, here’s a fairly basic one – how to force a textbox to accept only numeric input. Somebody asked me this today on a support call so I did a few quick lookups online and found the solutions listed rather unsatisfying. The main problem with most of the examples I could dig up was that they only include numeric values, but that provides a rather lame user experience. You need to still allow basic operational keys for a textbox – navigation keys, backspace and delete, tab/shift tab and the Enter key - to work or else the textbox will feel very different than a standard text box.

Yes there are plug-ins that allow masked input easily enough but most are fixed width which is difficult to do with plain number input. So I took a few minutes to write a small reusable plug-in that handles this scenario. Imagine you have a couple of textboxes on a form like this:

    <div class="containercontent">
    
         <div class="label">Enter a number:</div>
        <input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" />

         <div class="label">Enter a number:</div>
        <input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
    </div>

and you want to restrict input to numbers. Here’s a small .forceNumeric() jQuery plug-in that does what I like to see in this case:

[Updated thanks to Elijah Manor for a couple of small tweaks for additional keys to check for]

     <script type="text/javascript">
         $(document).ready(function () {
             $(".numberinput").forceNumeric();
         });


         // forceNumeric() plug-in implementation
         jQuery.fn.forceNumeric = function () {

             return this.each(function () {
                 $(this).keydown(function (e) {
                     var key = e.which || e.keyCode;

                     if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                     // numbers   
                         key >= 48 && key <= 57 ||
                     // Numeric keypad
                         key >= 96 && key <= 105 ||
                     // comma, period and minus, . on keypad
                        key == 190 || key == 188 || key == 109 || key == 110 ||
                     // Backspace and Tab and Enter
                        key == 8 || key == 9 || key == 13 ||
                     // Home and End
                        key == 35 || key == 36 ||
                     // left and right arrows
                        key == 37 || key == 39 ||
                     // Del and Ins
                        key == 46 || key == 45)
                         return true;

                     return false;
                 });
             });
         }
     </script>

With the plug-in in place in your page or an external .js file you can now simply use a selector to apply it:

$(".numberinput").forceNumeric();

The plug-in basically goes through each selected element and hooks up a keydown() event handler. When a key is pressed the handler is fired and the keyCode of the event object is sent. Recall that jQuery normalizes the JavaScript Event object between browsers. The code basically white-lists a few key codes and rejects all others. It returns true to indicate the keypress is to go through or false to eat the keystroke and not process it which effectively removes it.

Simple and low tech, and it works without too much change of typical text box behavior.

Make Donation
Posted in JavaScript  jQuery  HTML  


Feedback for this Post

 
# re: Restricting Input in HTML Textboxes to Numeric Values
by John Idol April 22, 2011 @ 5:21am
Nice. For stuff like that I usually go with the masking plugin [http://digitalbush.com/projects/masked-input-plugin/] which allows the navigational keys etc:

// 2 numeric digits
$('.numericField').mask('?99');

But this looks like a nice lighter alternative if you just need that functionality.
# re: Restricting Input in HTML Textboxes to Numeric Values
by Pete April 22, 2011 @ 7:24am
This is a great example of how to do a plugin for JQuery. You might want to look at jQuery AlphaNumeric by Paulo P. Marinas. This plugin limits input in all sorts of cool ways.
The example page is at http://www.manukalodgenz.com/js/
# re: Restricting Input in HTML Textboxes to Numeric Values
by Boiss April 22, 2011 @ 7:24am
Nice but I think that you could right click then paste something not numeric in that input.
# re: Restricting Input in HTML Textboxes to Numeric Values
by Mischa Kroon April 22, 2011 @ 3:07pm
This gets more complicated when you want to support:
10.50
and
10,50

Depending on culture settings.
# re: Restricting Input in HTML Textboxes to Numeric Values
by sansknowlede April 24, 2011 @ 11:34pm
nice one,
we used to have a separate js file which contains all the necessary activities like text only , number only, date diff etc. and using jquery bind to the textbox.
# re: Restricting Input in HTML Textboxes to Numeric Values
by Hemanshu Bhojak April 25, 2011 @ 12:14am
This does not work when you copy and paste in the text box.
# re: Restricting Input in HTML Textboxes to Numeric Values
by Rick Strahl April 25, 2011 @ 1:24am
Yes this doesn't work for *validating* numeric input, so if you paste this doesn't do the trick. But that's not the focus of this little plug-in - that's validation plug-ins are for. The goal here is to restrict the user input while typing so that invalid characters are not entered.

Definitely could do with additional characters though for separators, decimal points and negative number symbols. Will add that when I get a minute.
# Force Numeric value in TextBox
by Biztalk Musings April 25, 2011 @ 8:07am
Force Numeric value in TextBox
# re: Restricting Input in HTML Textboxes to Numeric Values
by John Walker May 04, 2011 @ 8:11pm
@Pete +1 for jQuery AlphaNumeric by Paulo P. Marinas.
# Annoying.
by Rik May 05, 2011 @ 7:09am
Please don't do this. It's really annoying. Validate, yes. Don't try to mess with how I type, though.
# re: Restricting Input in HTML Textboxes to Numeric Values
by Rick Strahl May 07, 2011 @ 6:03am
Updated the snippet with a few additional features based on comment feedback. Added numeric keypad and allow for decimal/thousand separator. No attempt at formatting is made.

Lot of comments that this won't solve all numeric entry problems and that's very true - it's not meant to. This is supposed to act as an input aid. You will still need to validate the final input for proper formatting etc. either client side or on the server.
# Good work
by Matt June 18, 2011 @ 2:44pm
Nice piece of work - as you say, it's not a validator, but an entry aid.

@Rick - sometimes, when users & the readers of form entries aren't computer literate, we do need to restrict what people can type, to limit confusion.
# re: Restricting Input in HTML Textboxes to Numeric Values
by Pete July 15, 2011 @ 1:31pm
You should add key == 110 for the numpad decimal point.
# re: Restricting Input in HTML Textboxes to Numeric Values
by Rick Strahl July 18, 2011 @ 5:30pm
@Pete - added, thanks.
# re: Restricting Input in HTML Textboxes to Numeric Values
by kupissimo January 12, 2012 @ 5:57am
Additional fixes:
1. allow only one decimal separator
2. fix decimal places

var decSeparator =".";//or ","
(function(jQuery) {
    function internalCheck(code, ch, key, v) {
        if (key==code)
            if (ch==decSeparator) {
                    if (v.indexOf(decSeparator)!=-1) 
                        return false;
            } else {
                return false;
            }
        return true;
    }
 
    jQuery.fn.forceNumeric = function (options) {
        var opts = jQuery.extend({}, jQuery.fn.forceNumeric.defaults, options);
    
        return this.each(function () {
            var o = jQuery.meta ? jQuery.extend({}, opts, $this.data()) : opts;
            $(this).keydown(function (e) {
                var key = e.which || e.keyCode;
                
                if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                // numbers   
                    key >= 48 && key <= 57 ||
                // Numeric keypad
                    key >= 96 && key <= 105 ||
                // comma, period and minus, . on keypad      '
                   key == 190 || key == 188 || key == 109 || key == 110 || key == 222 ||
                // Backspace and Tab and Enter
                   key == 8 || key == 9 || key == 13 ||
                // Home and End
                   key == 35 || key == 36 ||
                // left and right arrows
                   key == 37 || key == 39 ||
                // Del and Ins
                   key == 46 || key == 45) {
                    var v=$(this).val();
                
                    var tmp =internalCheck(190,".",key,v);
                    if (!tmp) return false;
                    
                    var tmp =internalCheck(188,",",key,v);
                    if (!tmp) return false;
    
                    return true;
                } else if (e.ctrlKey){
                    //ctrl-c       ctrl-v       ctrl-x
                    if (key==67 || key==86  || key==90)
                        return true;
                }
                return false;
            });
            
            $(this).blur(function (e) {
                var v=jQuery.trim($(this).val());
                if (v=='') {
                    return;
                }
                
                if(o.fixDecimals!=-1) {
                    var num = parseFloat(v);
                    var numSix =  num.toFixed(o.fixDecimals);
                    $(this).val(numSix);
                }
    
            });
            
            
        });   
        jQuery.fn.forceNumeric.defaults = {
                fixDecimals : -1
            };
    };
})(jQuery);
# re: Restricting Input in HTML Textboxes to Numeric Values
by Ares January 30, 2012 @ 11:40pm
this program works fine except that it doesn't allow to enter Numeric keypad values from laptop as we have to press Fn key to use those on laptop
# re: Restricting Input in HTML Textboxes to Numeric Values
by Speed March 08, 2012 @ 9:20am

how i can restrict numbers and restrict ctrl-c,ctrl-c in textbox with jquery
# re: Restricting Input in HTML Textboxes to Numeric Values
by Rick Strahl March 08, 2012 @ 2:38pm
@Speed - I recommend you check out my key code checker which makes it easy to find the key codes to block or perform special actions for. http://www.west-wind.com/WestwindWebToolkit/samples/Ajax/html5andCss3/keycodechecker.aspx

Check for keycode 67 and e.ctrlKey set inside of keydown:

if (!e.ctrlKey && e.which == 67)
  return false;  // cancel event bubbling
# re: Restricting Input in HTML Textboxes to Numeric Values
by Metalcoder May 07, 2012 @ 12:22pm
@kupissimo

To process CTRL+X, this:

 //ctrl-c       ctrl-v       ctrl-x
 if (key==67 || key==86  || key==90)
                        return true;


should be this:

 //ctrl-c       ctrl-v       ctrl-x
 if (key==67 || key==86  || key==88)
                        return true;


Or I'm missing something?
# re: Restricting Input in HTML Textboxes to Numeric Values
by Aurélien December 12, 2012 @ 6:08am
This is interesting javascript, I learned a lot of things, thanks, but there is a *big* problem: on French keyboards (and probably for many other countries as well), you have to press Shift in order to type digits. So your plugin actually allows French users to type things like &é"' but they cannot type any digits at all. This is very frustrating, and a showstopper as far as I am concerned. Sorry...
Since people have so many different keyboard layouts, I would recommend never using the keyCode at all (unless perhaps for things like games, where you don't care what the actual character is). I would recommend instead the validation approach: let the user type whatever she likes, and fix the result upon validation (or when the input loses focus) by reading the actual content of the field, and using regular expressions.
Cheers.
# re: Restricting Input in HTML Textboxes to Numeric Values
by ping tab January 09, 2013 @ 5:39pm
I have a question, how do you restrict text input from bad <script>?
say, I want to know if the input text included a <script>....</script>, how do I restrict it from users?
# re: Restricting Input in HTML Textboxes to Numeric Values
by Arto February 26, 2013 @ 10:35pm
what about for this inputs? -12.3 (valid) -12.-3 or 12.-3 (invalid)
# re: Restricting Input in HTML Textboxes to Numeric Values
by Manoj M September 16, 2013 @ 11:50pm
Hello,

Is there a way to avoid user from pasting non-numeric values in textbox and allowing only numeric values to copy-paste.

If you have some code for this then kindly paste it. It will be really helpful.

Cheers,
Manoj
 


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2014