1

I want to validate a text box so that it only takes numeric values. If the user tries to press alphabet keys, the keystrokes must be ignored, i.e nothing can be typed in.

How can this be done?

2
  • Why bother? You only care if the field is valid when the form is posted, it doesn't matter what value it has in the meantime. Commented Jun 30, 2011 at 14:22
  • Try using onchange and a hidden input. Every time they change the input (such as copy-paste/type), it should run your script. If the input is valid, commit the change to the hidden input, otherwise, revert to the previous state by copying from the hidden input. Commented Aug 3, 2011 at 21:57

7 Answers 7

1

Use this code in your HTML page:

    <HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
</HTML>
Sign up to request clarification or add additional context in comments.

Comments

0

You might need to use the onkeypress event.

An example which does the opposite thing (input field accepts everything but numbers) can be found here: http://www.w3schools.com/jsref/event_onkeypress.asp

Comments

0

how about somthing similar to this

//Bind this keypress function to all of the input tags
$("input").keypress(function (evt) {
//Deterime where our character code is coming from within the event
var charCode = evt.charCode || evt.keyCode;
if (IsNumeric(charCode)) { //key's keycode
return false;
}
});

Comments

0

W3C recommends using the oninput event, which is future proof and takes care of devices which do not have a keyboard. If your targeted browsers support oninput, do not use any keyboard events.

4 Comments

I agree, but it's not supported in IE < 9 and it's not cancellable.
@Tim It doesn't really need to be cancellable -- just adjust the element's value appropriately.
@user349433: Adjusting the input's value after the event has fired requires knowledge of its value immediately prior to the event and doing potentially complicated comparisons.
@Tim: Not necessarily. For example, in the case of this particular question, you could just do this.value = this.value.replace(/\D+/g, '').
0

You can make a javascript function that you will call everytime you press a key in your textbox (with the onkeypress event).

  function isNumberKey(evt)
  {
     var charCode = (evt.which) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

     return true;
  }

Code sample source

Comments

0

I recently was dealing with the same situation (but opposite -- I wanted only alphabetic characters). I initially considered simply using the keypress event, but that has a few fatal flaws:

  • The user can still paste invalid data into the field;
  • The user can drag invalid text into the field;
  • Cancelling the keypress invalidates certain valid input (e.g., hotkeys) unless you take special care regarding meta keys (which I'm not positive is possible to do in a robust, complete, and portable manner);
  • Autocomplete;
  • And so on for any number of non-keyboard input methods.

Fortunately, at least Firefox and IE9 have a solution: they have an input event that fires for any manner of input method, whether it's a keystroke or a paste operation or whatever. IE<9 doesn't have that, but they do have a paste event to handle the most common use-case, but take care that it fires before the paste actually occurs, so you have to cancel the paste and then do most of the (IE-specific) paste work manually (just a couple of lines of code, but still a bit annoying).

I was developing for an internal network that didn't support other browsers, so I haven't researched what WebKit has available. The DOM Level 3 spec has a textinput event, but at least Firefox does not support it yet.

1 Comment

I'm not sure the textInput event is going to gain any more traction now that the input event exists (it's implemented in WebKit and Opera, by the way).
0

With HTML5 in modern browsers you can use <input type="number"> (see Dive Into HTML5 for some examples). You'll need a fallback for older browsers though, so here you go. This works in all major browsers. It won't prevent the user from pasting or dragging in non-numeric content, however.

jsFiddle: http://jsfiddle.net/JCUT2/

var textBox = document.getElementById("foo");

textBox.onkeypress = function(e) {
   e = e || window.event;
   var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
   if (/\D/.test(String.fromCharCode(charCode))) {
       return false;
   }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.