43

I'm using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY rejects all other key inputs, like ctrl-A to select the text, or even any other browser functions like ctrl-T or ctrl-W while the text box is selected. Does anyone know of a better script to only allow numerical input, but not block normal commands (that aren't being directly input into the field)? Thanks Here is the code I'm using now:

function numbersonly(e, decimal) 
{
    var key;
    var keychar;

    if (window.event) 
        key = window.event.keyCode;
    else if (e) 
        key = e.which;
    else 
        return true;

    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27))
       return true;     
    else if ((("0123456789").indexOf(keychar) > -1))
       return true;
    else if (decimal && (keychar == "."))
       return true;        
    else
       return false;
}

Edit: None of the solutions provided have solved my problem of allowing commands like ctrl-A while the text box is selected. That was the whole point of my asking here, so I have gone back to using my original script. Oh well.

Hulk1991
  • 3,079
  • 13
  • 31
  • 46
RobHardgood
  • 550
  • 1
  • 8
  • 17
  • 3
    If you're happy using HTML 5, imperfectly implemented, form type `` that can work. – David Thomas Sep 21 '10 at 22:02
  • I wish i could use HTML 5. That was my first thought, and it would have saved me so much time looking up javascript :-p thanks anyway – RobHardgood Sep 21 '10 at 22:13
  • Possible duplicate of [HTML Text Input allow only Numeric input](http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input) – Pineda Dec 02 '16 at 13:13

30 Answers30

36

This is something I made another time for just numbers, it will allow all the formatters as well.

jQuery

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();
});​

Try it

http://jsfiddle.net/zpg8k/

As a note, you'll want to filter on submit/server side as well, for sake of pasting/context menu and browsers that don't support the paste event.

Edit to elaborate on multiple methods

I see you're bouncing around the 'accepted' answer, so I'll clear something up. You can really use any of the methods listed here, they all work. What I'd personally do is use mine for live client side filtering, and then on submit and server side use RegEx as suggested by others. However, no client side by itself will be 100% effective as there is nothing stopping me from putting document.getElementById('theInput').value = 'Hey, letters.'; in the console and bypassing any clientside verification (except for polling, but I could just cancel the setInterval from the console as well). Use whichever client side solution you like, but be sure you implement something on submit and server side as well.

Edit 2 - @Tim Down

Alright, per the comments I had to adjust two things I didn't think of. First, keypress instead of keydown, which has been updated, but the lack of indexOf in IE (seriously Microsoft!?) breaks the example above as well. Here's an alternative

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!($.inArray(k,a)>=0))
        e.preventDefault();
});​

New jsfiddle: http://jsfiddle.net/umNuB/

Robert
  • 21,110
  • 9
  • 55
  • 65
  • Hmm, I'm not sure this will work for me. It still seems to allow letters if you hold down the key. I want to prevent letters entirely, so that a form validation error is the last resort – RobHardgood Sep 21 '10 at 22:04
  • It's not allowing letters for me. As I said this was something I built before that had letters as well, but I removed that portion, make sure you're looking at the right jsfiddle. – Robert Sep 21 '10 at 22:06
  • It allows because someone messes around with his jsfiddle. Paste his javascript and you get what you want. – sod Sep 21 '10 at 22:06
  • Ohh, I see. You're right, I didn't notice the code was different. Can you explain what all those numbers are for var a? Are they the key codes for the numerical keys? – RobHardgood Sep 21 '10 at 22:08
  • 2
    The numbers are the formatters, backspace, shift etc etc etc. As you press a key it should show the keycode to the right, so you can play around and see what you want to allow and disallow. – Robert Sep 21 '10 at 22:09
  • Great! I think this will work perfectly :) thanks for explaining it too. – RobHardgood Sep 21 '10 at 22:10
  • @fahd: As noted in the "make sure you verify server and on submit". – Robert Sep 21 '10 at 22:32
  • Sorry for the checkmark switching, I didn't realize you could only mark one (i'm a new member) but I'm using this solution. Thanks again Robert – RobHardgood Sep 21 '10 at 22:36
  • 8
    Don't use `keydown` or `keyup` for checking the character the user has typed. Any success you get will be coincidental and unreliable: a differently laid out keyboard or a keyboard from a culture other than your own will have different key mappings and your key codes will be useless. The only event that contains character information is `keypress`. – Tim Down Sep 21 '10 at 23:50
  • @Tim Down: A very valid point, I didn't think of that. Updated answer, hopefully Rob sees the notification. – Robert Sep 22 '10 at 00:04
  • 2
    One other issue: in IE up to and including version 8, arrays don't have an `indexOf` method. – Tim Down Sep 22 '10 at 00:11
  • 1
    Hmm @Tim Down, full of helpful tidbits that make me hate IE more, adjusted again. – Robert Sep 22 '10 at 00:23
  • What browser commands? I can still backspace etc etc. Which command specifically? – Robert Sep 22 '10 at 01:45
  • I'm talking about ctrl-A to highlight all the text in the field, and ctrl-T to open a new tab, etc. Usually they work find inside text fields. Using firefox – RobHardgood Sep 22 '10 at 01:48
  • Hmm they still work in Chrome, but not FireFox. It appears to be the way that FireFox handles the events, with Chrome intercepting the event before it's passed to the form, but Firefox not. I'll have to think a bit of a way to get around that... – Robert Sep 22 '10 at 01:56
  • Interesting... I just tried it in Opera and Safari too, and it works in Opera but not Safari. – RobHardgood Sep 22 '10 at 01:58
  • Also, what do you think would be the best way to call this function from my tag? Or should it load when the page loads? I'm still kind of new to JS... – RobHardgood Sep 22 '10 at 02:04
  • I don't think there's a way around the FireFox problem because FireFox fires the event to the input as if it was just the key being pressed, not ctrl+key. As far as implementation, this uses a jQuery selector, so you'd use a selector equivalent to your input element. Non-jQuery would be something like `document.getElementById('elementId').onkeypress = function() {` then the rest stays the same except `e.preventDefault();` would change to `return false;` – Robert Sep 22 '10 at 02:32
  • Ah, I see. Thanks. Let me know if you think of a solution for this firefox thing... – RobHardgood Sep 22 '10 at 03:28
  • I have 2 points, 1) Your code doesn't work on an Android Phone 2) You have written a loop inside a keypress event. So every time i hit a key, it'll iterate through the loop. Either shift your loop outside the keypress event or just do something what "hofnarwillie" mentioned – wOlVeRiNe Feb 18 '14 at 05:47
  • jQuery for the win!? https://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/19492#19492 ;) – Volker E. May 02 '14 at 18:04
20

This works in IE, Chrome AND Firefox:

<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" />
Hamund
  • 706
  • 11
  • 19
17
     .keypress(function(e)
               {
                 var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];

                 if (!($.inArray(e.which, key_codes) >= 0)) {
                   e.preventDefault();
                 }
               });

You need Backspace and Delete keys too ;)

ialpert
  • 370
  • 3
  • 8
  • 2
    I am befuddled that it's not included in the top answer. Perhaps an edit is necessary? – th3byrdm4n Mar 25 '13 at 00:37
  • This was the only solution that works on all platforms. Thank you for being awesome! – Emi May 20 '15 at 20:53
  • `.on('keypress', function (event) { var _element = $(this), keyCode = event.keyCode || event.which, keysAllowed = [44, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8, 9, 13]; if ($.inArray(keyCode, keysAllowed) === -1 && event.ctrlKey === false) { event.preventDefault(); } });` it also add tab and enter and watch for ctrl combination. – Arkadiusz Rosłaniec Aug 04 '15 at 13:10
12

http://jsfiddle.net/PgHFp/

<html>
<head>
<title>Test</title>
<script language="javascript">
function checkInput(ob) {
  var invalidChars = /[^0-9]/gi
  if(invalidChars.test(ob.value)) {
            ob.value = ob.value.replace(invalidChars,"");
      }
}
</script>
</head>

<body>
    <input type="text" onkeyup="checkInput(this)"/>
</body>
</html>
dogbane
  • 266,786
  • 75
  • 396
  • 414
5

I use this:

    oEl.keypress(function(ev)
    {
        var sKey = String.fromCharCode(ev.which);
        if (!sKey.match(/[0-9]/) || !sKey === "") 
            ev.preventDefault();            
    });

The advantage is, that every key which does not provide an input to the field is still allowed, so you don't have to worry about every single special key. Even combos like CTRL + R do still work.

EDIT As this is not working in Firefox I had to modify the function a little:

    oEl.keypress(function(ev)
    {
        var iKeyCode = ev.which || ev.keyCode;
        var aSpecialKeysForFirefox = [8, 9, 13, 27, 37, 38, 39, 40, 46];
        var sKey = String.fromCharCode(iKeyCode);
        if (sKey !== "" && $.inArray(iKeyCode, aSpecialKeysForFirefox ) < 0 && !sKey.match(/[0-9]/)) {
            ev.preventDefault();
        }
    });

Explanation All Browsers handle jquerys keypress event differently. To make it work in FF the $.inArray check is added. As firefoxs keypress-event doesn't trigger when combinations like strg+tab are used, but the others do, the key.match approach still adds a little value to the latter, as it enables those combinations.

hugo der hungrige
  • 12,382
  • 9
  • 57
  • 84
5

Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.

var numInput;
window.onload = function () {   
    numInput = document.getElementById('numonly');
    numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
    {
        numInput.value = numInput.value.replace(/[^0-9]+/,"");
    }
}
Randy the Dev
  • 25,810
  • 6
  • 43
  • 54
5

The only event that contains information about the character typed is keypress. Anything character-related you may infer from the keyCode property of keydown or keyup events is unreliable and dependent on a particular keyboard mapping. The following will prevent non-numeric keyboard input all major browsers by using the character obtained from the keypress event. It won't prevent the user from pasting or dragging non-numeric text in.

var input = document.getElementById("your_input");

input.onkeypress = function(evt) {
    evt = evt || window.event;
    if (!evt.ctrlKey && !evt.metaKey && !evt.altKey) {
        var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
        if (charCode && !/\d/.test(String.fromCharCode(charCode))) {
            return false;
        }
    }
};
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • @Tim Down this works well too, but again, it won't allow me to use functions like ctrl-A within the text box – RobHardgood Sep 22 '10 at 21:58
  • @RobHargood, my comment explained why that's so, because Firefox passes ctrl-t etc etc as if you're pressing just t, there's no reliable way to completely block the t letter in Firefox while allowing control-t. You can be reactive instead of proactive if you want that functionality, using `replace` like some of the other examples here. – Robert Sep 22 '10 at 22:07
  • Good point. I've updated my answer to check for the Ctrl key being pressed. – Tim Down Sep 22 '10 at 22:20
  • Robert, you can entirely reliably distinguish between `t` and `Ctrl-t` using the `ctrlKey` property of the event. – Tim Down Sep 22 '10 at 22:38
  • @TimDown, it's not working for me even when checking for control, Firefox on Mac for me is firing into the textfield as if it was only t being pressed. – Robert Sep 23 '10 at 16:36
  • Really? It works fine for me on my Mac. What are you pressing and what's going wrong? – Tim Down Sep 23 '10 at 22:44
  • Yes. Cmd-T works fine for me within the input in Firefox 3.6. – Tim Down Sep 23 '10 at 23:28
  • Hmm, I made another jsfiddle again to test it and it's working now, maybe I copied something wrong... oh well. – Robert Sep 23 '10 at 23:45
4

Maybe you are using bootstrap. If so, this may suffice:

<input type="text" data-mask="9999999"> 

Input mask

ichigolas
  • 7,595
  • 27
  • 50
  • 1
    This only works for fixed-length fields. For example, if you might store numbers from 1 to 1000, your users would have to type `0001`. Not so friendly for that. Maybe for phone numbers, SSNs, etc. – Matt Johnson-Pint Mar 10 '13 at 20:05
3

Add <script type="text/javascript" src="jquery.numeric.js"></script> then use

 $("element").numeric({ decimal: false, negative: false });
IlludiumPu36
  • 4,196
  • 10
  • 61
  • 100
3

The following code is something I use extensively. I found the script in a forum, but modified and expanded it to accommodate my needs:

<script type="text/javascript">
    // Restrict user input in a text field
    // create as many regular expressions here as you need:
    var digitsOnly = /[1234567890]/g;
    var integerOnly = /[0-9\.]/g;
    var alphaOnly = /[A-Za-z]/g;
    var usernameOnly = /[0-9A-Za-z\._-]/g;

    function restrictInput(myfield, e, restrictionType, checkdot){
        if (!e) var e = window.event
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        var character = String.fromCharCode(code);

        // if user pressed esc... remove focus from field...
        if (code==27) { this.blur(); return false; }

        // ignore if the user presses other keys
        // strange because code: 39 is the down key AND ' key...
        // and DEL also equals .
        if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
            if (character.match(restrictionType)) {
                if(checkdot == "checkdot"){
                    return !isNaN(myfield.value.toString() + character);
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
    }
</script>

Different usage methods would be:

<!-- To accept only alphabets -->
<input type="text" onkeypress="return restrictInput(this, event, alphaOnly);">
<!-- To accept only numbers without dot -->
<input type="text" onkeypress="return restrictInput(this, event, digitsOnly);">
<!-- To accept only numbers and dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly);">
<!-- To accept only numbers and only one dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');">
<!-- To accept only characters for a username field -->
<input type="text" onkeypress="return restrictInput(this, event, usernameOnly);">
Nirmal
  • 9,391
  • 11
  • 57
  • 81
2

shorter way and easy to understand:

$('#someID').keypress(function(e) { 
    var k = e.which;
    if (k <= 48 || k >= 58) {e.preventDefault()};
});
serejja
  • 22,901
  • 6
  • 64
  • 72
ZAJDAN
  • 121
  • 1
  • 1
  • 5
  • This does not account for the shift key being held on US keyboards and it also disables the backspace key, which is not a desired effect. – BeanFlicker Mar 03 '16 at 18:53
2

This is a variation on Robert's answer that allows a single decimal point to be entered. If a decimal point has already been entered, only numbers are accepted as input.

JSFiddle - decimal number input

// Allow only decimal number input

$('#decimalInput').keypress(function (e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
    a.push(i);

    // allow a max of 1 decimal point to be entered
    if (this.value.indexOf(".") === -1) {
        a.push(46);
    }

    if (!(a.indexOf(k) >= 0)) e.preventDefault();

    $('span').text('KeyCode: ' + k);
});
Jon Crowell
  • 21,695
  • 14
  • 89
  • 110
2

I know that there are already many answers but for the sake of simplicity i would like to add another answer which is simple and self explanatory in which we do not have to remember keycodes and it also works across all browsers.

document.getElementById('myinput').onkeydown = function(e)
 {
     console.log(e.key);
     //console.log(e.target.value);
     switch (e.key)
     {
         case "1":
         case "2":
         case "3":
         case "4":
         case "5":
         case "6":
         case "7":
         case "8":
         case "9":
         case "0":
         case "Backspace":
             return true;
             break;

         case ".":
             if (e.target.value.indexOf(".") == -1)
             {
                 return true;
             }
             else
             {
                 return false;
             }
             break;

         default:
             return false;
     }

 }
<input type="text" placeholder="Enter Value" id="myinput" />
vibs2006
  • 6,028
  • 3
  • 40
  • 40
  • Nice, but we can't "TAB" out of the field, select everything with Ctrl+A... so it does not answer the question completely. – Damien Jan 16 '18 at 14:09
  • @Damien we can also easily do that by handling keyboard and mouse events. I have kept the example simple for sake of simplicity. – vibs2006 Jan 17 '18 at 05:20
1

this will enable the numpad inputs also.

.keydown(function(event){                                     
    if(event.keyCode == 8 || event.keyCode == 46)             
        return true;                                         
    if(event.keyCode >= 96 && event.keyCode <= 105)           
        return true;                                          
    if(isNaN(parseInt(String.fromCharCode(event.keyCode),10)))
       return false;                                          
}); 
Yunus Eren Güzel
  • 3,018
  • 11
  • 36
  • 63
1

In order to block anything but numbers from being input into a text field but still allowing for other buttons to work (such as delete, shift, tab, etc.) look at a reference of the Javascript key codes; anything from 65 on up (to 222) can be blocked.

Using Jquery and Javascript, that would look like:

$('#textFieldId').keydown(function(event) {
    if ( event.keyCode > 64 ) {
        event.preventDefault();
    }
});

The key codes will be the same in Javascript whether or not Jquery is used.

Asher G.
  • 4,903
  • 5
  • 27
  • 30
  • This looks good to me, although [event.which](http://api.jquery.com/event.which/) is preferred to normalize the key codes. – Andy G May 14 '16 at 09:19
  • (I should say, the code looks good for *my* purpose, unfortunately not the OP's requirement though ;)) – Andy G May 14 '16 at 11:30
1

Here is my solution: a combination of the working ones below.

var checkInput = function(e) {
        if (!e) {
            e = window.event;
        }

        var code = e.keyCode || e.which;

        if (!e.ctrlKey) {

            //46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
            if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
                return true;
            //35..39 - home, end, left, right
            if (code >= 35 && code <= 39)
                return true;
            //numpad numbers
            if (code >= 96 && code <= 105)
                return true;
            //keyboard numbers
            if (isNaN(parseInt(String.fromCharCode(code), 10))) {
                e.preventDefault();
                return false;
            }
        }
        return true;
    };
Uygar
  • 11
  • 1
1

I came across your question while trying to figure this out myself. Here is the solution that I came up with.

// Prevent user from entering non-numeric characters in number boxes.
(function (inputs) {
    var input;
    var f = function (e) {
        var unicodeRe = /U\+(\d+)/;
        // Chrome doesn't support the standard key property, so use keyIdentifier instead.
        // Instead of the actual character that "key" returns, keyIdentifier returns
        // A string such as "U+004F" representing the unicode character.

        // For special characters (e.g., "Shift", a string containing the name of the key is returned.)
        var ch = e.key || e.keyIdentifier;
        var match = ch.match(unicodeRe);
        // keyIdentifier returns a unicode. Convert to string.
        if (match) {
            ch = String.fromCharCode(Number.parseInt(match[1], 16));
        }
        console.log(ch);
        if (ch.length === 1 && /[^0-9]/.test(ch)) {
            if (!/[\b]/.test(ch)) { // Don't prevent backspace.
                e.preventDefault();
            }
        }
    };
    for (var i = 0, l = inputs.length; i < l; i += 1) {
        input = inputs[i];
        input.onkeydown = f;
    }
}(document.querySelectorAll("input[type=number],#routeFilterBox")));

Edit: I've discovered that my solution does not allow the user to enter numbers via the numpad in Chrome. The 0-9 keypad keys seem to be returning the character "`" for 0 and A-I for the rest of the number keys.

1

It's worth pointing out that no matter how tightly you manage to control this via the front end (Javascript, HTML, etc), you still need to validate it at the server, because there's nothing to stop a user from turning off javascript, or even deliberately posting junk to your form to try to hack you.

My advice: Use the HTML5 markup so that browsers which support it will use it. Also use the JQuery option previously suggested (the inital solution may have flaws, but it seems like the comments have been working through that). And then do server-side validation as well.

Spudley
  • 166,037
  • 39
  • 233
  • 307
1

All of the answers are outdated, lengthy and will cause annoyance to your users. Most of them don’t even filter or allow pasted content.

Instead of filtering the input, do some validation before submitting the form and then also server-side.

HTML has validation included:

<input type="number" pattern="[0-9]+">

This also enables the number keyboard on mobile.

fregante
  • 29,050
  • 14
  • 119
  • 159
0

This is my plugin for that case:

 (function( $ ) {
    $.fn.numbers = function(options) {
      $(this).keypress(function(evt){
          var setting = $.extend( {
                'digits' : 8
              }, options);
          if($(this).val().length > (setting.digits - 1) && evt.which != 8){
              evt.preventDefault(); 
          }
          else{
              if(evt.which < 48 || evt.which > 57){
                if(evt.keyCode != 8){
                    evt.preventDefault();  
                }
              }
          }
      });
    };
  })( jQuery );

Use:

 $('#limin').numbers({digits:3});
 $('#limax').numbers();
jortsc
  • 308
  • 2
  • 11
0

There is my current solution of numeric input, need to test in different browsers but seems to work

Support comma and period delimiter (czech native is comma), space and numpad/keyboard numbers input. Allow Ctrl+C Ctrl+A or Ctrl+X, arrow navigation and delete block Ctrl+V. React on escape key by blurring input.

Watch my Coffee script:

(($) ->
  $.fn.onlyNumbers = ->
    @each ->
      $(@).keydown (e) ->
        # get code of key
        code = if e.keyCode then e.keyCode else e.which

        return $(@).blur() if code is 27 # blur on escape
        return if code in [46, 8, 9, 13] # 46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
        return if (e.ctrlKey or e.metaKey) and code in [65, 67, 88] # ctrl|command + [a, c, x]
        return if code in [96..105] # numpad numbers
        return if code in [48..57] # numbers on keyboard
        return if code in [35..39] # 35..39 - home, end, left, right
        return if code in [188, 190, 32] # comma, period, space
        return if code in [44] # comma, period,

        e.returnValue = false # IE hate you
        e.preventDefault();

      $(@).keypress (e) ->
        code = if e.keyCode then e.keyCode else e.which
        return if code in [44, 46, 32] # comma, period, space
        return if code in [48..57] # numbers on keyboard
        e.returnValue = false # IE hate you
        e.preventDefault();

) jQuery

You can get compiled Javascript here http://goo.gl/SbyhXN

OzzyCzech
  • 9,713
  • 3
  • 50
  • 34
0

My functions:

$('.input_integer_only').on('input', function(e) {
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
});


$('.input_float_only').on('input', function(e) {
    var $var = $(this).val().replace(/[^0-9\.]/g, '');
    var $aVar = $var.split('.');

    if($aVar.length > 2) {
        $var = $aVar[0] + '.' + $aVar[1];
    }

    $(this).val($var);
});
Tin Nguyen
  • 285
  • 1
  • 3
  • 6
0

You can make changes to accept the keycode for Ctrl keys: 17, 18, 19, 20. Then your code will be like:

function numbersonly(e, decimal) {
var key;
var keychar;

if (window.event) 
    key = window.event.keyCode;
else if (e) 
    key = e.which;
else 
    return true;

keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) || (key==17) || (key==18) || (key==19) || (key==20))
   return true;     
else if ((("0123456789").indexOf(keychar) > -1))
   return true;
else if (decimal && (keychar == "."))
   return true;        
else
   return false;
}
0
  document.getElementById('myinput').onkeydown = function(e) {
      if(!((e.keyCode > 95 && e.keyCode < 106)
      || (e.keyCode > 47 && e.keyCode < 58) 
      || e.keyCode == 8
      || e.keyCode == 9)) {
        return false;
      }
  }
Harley
  • 1,305
  • 1
  • 13
  • 28
0

You can do like this to accept only Numbers in text Box,

 function onChange(event){
   var ckeckChars = /[^0-9]/gi;
   if(checkChars.test(event.target.value)) {
        event.target.value = event.target.value.replace(ckeckChars,"");
  }
Venkatesh Somu
  • 4,710
  • 4
  • 23
  • 22
0

This JavaScript function will be used to restrict alphabets and special characters in Textbox , only numbers, delete, arrow keys and backspace will be allowed. JavaScript Code Snippet - Allow Numbers in TextBox, Restrict Alphabets and Special Characters

Tested in IE & Chrome.

JavaScript function

<script type="text/javascript">
    /*code: 48-57 Numbers
      8  - Backspace,
      35 - home key, 36 - End key
      37-40: Arrow keys, 46 - Delete key*/
    function restrictAlphabets(e){
        var flag = false;
var x = e.which || e.keycode;
if ((x >= 48 && x <= 57) || x == 8 ||
    (x >= 35 && x <= 40) || x == 46)
    flag = true;
else
    flag = false;

if (flag && e.keyCode === 46 && $(e.currentTarget).val().split('.').length === 2) {
    flag = false;
}

return flag;
    }
</script>

HTML Source Code with JavaScript

<html>
    <head>
        <title>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</title>
        <script type="text/javascript">
            /*code: 48-57 Numbers
              8  - Backspace,
              35 - home key, 36 - End key
              37-40: Arrow keys, 46 - Delete key*/
            function restrictAlphabets(e){
                var x=e.which||e.keycode;
                if((x>=48 && x<=57) || x==8 ||
                    (x>=35 && x<=40)|| x==46)
                    return true;
                else
                    return false;
            }
        </script>
    </head>
<body style="text-align: center;">
    <h1>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</h1>
    <big>Enter numbers only: </big>
    <input type="text" onkeypress='return restrictAlphabets(event)'/>
</body>

</html>

Refrence

Durgesh Pandey
  • 2,314
  • 4
  • 29
  • 43
0

I am using below in Angular to restrict character

in HTML

For Number Only

<input
 type="text"
 id="score"
 (keypress) ="onInputChange($event,'[0-9]')"
 maxlength="3"
 class="form-control"> 

for Alphabets Only

<input
     type="text"
     id="state"
     (keypress) ="onInputChange($event,'[a-zA-Z]')"
     maxlength="3"
     class="form-control"> 

In TypeScript

 onInputChange(event: any, inpPattern:string): void {   
        var input = event.key; 
        if(input.match(inpPattern)==null){
         event.preventDefault();
        }
      }
upog
  • 4,965
  • 8
  • 42
  • 81
0

You can use this JS code with RegEx validation:

function validateInput() {
    var inputValue = document.getElementById("inputBox").value;
    if (inputValue === "" || !/^\d+$/.test(inputValue)) {
        alert("Enter a positive integer:");
    } else {
        var RNUM = parseInt(inputValue);
    }
}
-1

You can handle te event on html by introducing keypresshandler function

function keypresshandler(event)
{
     var charCode = event.keyCode;

     //You condition
     if (charCode == 58 ){

        event.preventDefault();

        return false;
     }        
} 
slavoo
  • 5,798
  • 64
  • 37
  • 39
Priyanthi
  • 1,715
  • 2
  • 10
  • 7
-1

Javascript is often used on the browser client side to perform simple tasks that would otherwise require a full postback to the server. Many of those simple tasks involve processing text or characters entered into a form element on a web page, and it is often necessary to know the javascript keycode associated with a character. Here is a reference.

Press a key in the text box below to see the corresponding Javascript key code.

        function restrictCharacters(evt) {

            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (((charCode >= '48') && (charCode <= '57')) || (charCode == '44')) {
                return true;
            }
            else {
                return false;
            }
        }
Enter Text:
<input type="text" id="number" onkeypress="return restrictCharacters(event);" />
Mayur Narula
  • 150
  • 1
  • 4