Rectangle 27 271

If you want to restrict input (as opposed to validation), you could work with the key events. something like this:

<input type="text" class="numbersOnly" value="" />
jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.

You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.

+1 - I was going to suggest this same thing. It's a very good point to note that this form of validation can take place per keystroke, rather than once at the end. The only thing I'd add is some form of alert that what the user is typing is being rejected. Simply not showing the letters will make all-too-many people think their keyboard is broken. perhaps subtly change the background or border colour.. just as long as the user knows that your app is actually doing something.

agreed. i have an example at tarbuilders.com. if you click "contact", the form checks the user input on the fly and if it's valid, there's a green border and check mark. invalid -> red and "x"

annoying that you can't use the arrow keys to move over the characters...

CRAP, if I write numbers i.e "123", and then press a letter key, i.e "a" it empty the input...

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 271

If you want to restrict input (as opposed to validation), you could work with the key events. something like this:

<input type="text" class="numbersOnly" value="" />
jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.

You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.

+1 - I was going to suggest this same thing. It's a very good point to note that this form of validation can take place per keystroke, rather than once at the end. The only thing I'd add is some form of alert that what the user is typing is being rejected. Simply not showing the letters will make all-too-many people think their keyboard is broken. perhaps subtly change the background or border colour.. just as long as the user knows that your app is actually doing something.

agreed. i have an example at tarbuilders.com. if you click "contact", the form checks the user input on the fly and if it's valid, there's a green border and check mark. invalid -> red and "x"

annoying that you can't use the arrow keys to move over the characters...

CRAP, if I write numbers i.e "123", and then press a letter key, i.e "a" it empty the input...

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 188

I've successfully implemented many forms with jquery.numeric plugin.

$(document).ready(function(){
    $(".numeric").numeric();
});

EDIT:- With wider support for newer HTML standards, we can use pattern attribute and number type for input elements to restrict number only input. It works to restrict pasting non-numeric content as well. More information about number and other newer input types is available here.

@Darryl the source is only a few dozen lines long, so I'm sure modifying it to allow that is trivial. I just found this plugin and modified it so that there is now an allowDecimal option for whenever I only want to allow integer values.. the source is very simple and well written.

This does not work when copy-pasting into input fields which are of type="number".

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 188

I've successfully implemented many forms with jquery.numeric plugin.

$(document).ready(function(){
    $(".numeric").numeric();
});

EDIT:- With wider support for newer HTML standards, we can use pattern attribute and number type for input elements to restrict number only input. It works to restrict pasting non-numeric content as well. More information about number and other newer input types is available here.

@Darryl the source is only a few dozen lines long, so I'm sure modifying it to allow that is trivial. I just found this plugin and modified it so that there is now an allowDecimal option for whenever I only want to allow integer values.. the source is very simple and well written.

This does not work when copy-pasting into input fields which are of type="number".

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 51

The jquery.numeric plugin has some bugs that I notified the author of. It allows multiple decimal points in Safari and Opera, and you can't type backspace, arrow keys, or several other control characters in Opera. I needed positive integer input so I ended up just writing my own in the end.

$(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});

+1, but needs to allow a negative number too.

Its not possible to enter a 0 at all using this code. Tested with Chrome and FF on Mac.

I updated this in order to accept 0 digit (48 == event.which && ($(this).val() > 0 )) || // No 0 first digit

This is the most clever and functional option, thank you very much for this.

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 51

The jquery.numeric plugin has some bugs that I notified the author of. It allows multiple decimal points in Safari and Opera, and you can't type backspace, arrow keys, or several other control characters in Opera. I needed positive integer input so I ended up just writing my own in the end.

$(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});

+1, but needs to allow a negative number too.

Its not possible to enter a 0 at all using this code. Tested with Chrome and FF on Mac.

I updated this in order to accept 0 digit (48 == event.which && ($(this).val() > 0 )) || // No 0 first digit

This is the most clever and functional option, thank you very much for this.

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 97

I thought that the best answer was the one above to just do this.

jQuery('.numbersOnly').keyup(function () {  
    this.value = this.value.replace(/[^0-9\.]/g,''); 
});

but I agree that it is a bit of a pain that the arrow keys and delete button snap cursor to the end of the string ( and because of that it was kicked back to me in testing)

I added in a simple change

$('.numbersOnly').keyup(function () {
    if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
       this.value = this.value.replace(/[^0-9\.]/g, '');
    }
});

this way if there is any button hit that is not going to cause the text to be changed just ignore it. With this you can hit arrows and delete without jumping to the end but it clears out any non numeric text.

For better performance create a var with replace result instead of running it twice.

keypress could be used to further simplify this, because apparently keyup and keydown trigger on any keyboard key, whereas keypress only triggers on "character" keys (thus not triggering on the arrow and delete keys). See this answer for reference: stackoverflow.com/a/1367720/1298685

@IanCampbell keypress means you can input a character to begin with that doesnt get removed. Won't work. Keydown does the same thing. I can only make it work with keyup.

thank you very much =)

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 97

I thought that the best answer was the one above to just do this.

jQuery('.numbersOnly').keyup(function () {  
    this.value = this.value.replace(/[^0-9\.]/g,''); 
});

but I agree that it is a bit of a pain that the arrow keys and delete button snap cursor to the end of the string ( and because of that it was kicked back to me in testing)

I added in a simple change

$('.numbersOnly').keyup(function () {
    if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
       this.value = this.value.replace(/[^0-9\.]/g, '');
    }
});

this way if there is any button hit that is not going to cause the text to be changed just ignore it. With this you can hit arrows and delete without jumping to the end but it clears out any non numeric text.

For better performance create a var with replace result instead of running it twice.

keypress could be used to further simplify this, because apparently keyup and keydown trigger on any keyboard key, whereas keypress only triggers on "character" keys (thus not triggering on the arrow and delete keys). See this answer for reference: stackoverflow.com/a/1367720/1298685

@IanCampbell keypress means you can input a character to begin with that doesnt get removed. Won't work. Keydown does the same thing. I can only make it work with keyup.

thank you very much =)

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 44

jQuery.isNumeric( value )
$.isNumeric( "-10" );     // true
$.isNumeric( 16 );        // true
$.isNumeric( 0xFF );      // true
$.isNumeric( "0xFF" );    // true
$.isNumeric( "8e5" );     // true (exponential notation string)
$.isNumeric( 3.1415 );    // true
$.isNumeric( +10 );       // true
$.isNumeric( 0144 );      // true (octal integer literal)
$.isNumeric( "" );        // false
$.isNumeric({});          // false (empty object)
$.isNumeric( NaN );       // false
$.isNumeric( null );      // false
$.isNumeric( true );      // false
$.isNumeric( Infinity );  // false
$.isNumeric( undefined ); // false

Here is an example of how to tie the isNumeric() in with the event listener

$(document).on('keyup', '.numeric-only', function(event) {
   var v = this.value;
   if($.isNumeric(v) === false) {
        //chop off the last char entered
        this.value = this.value.slice(0,-1);
   }
});

+1 for no plugins. I would like to add a slight change to allow thousands separetor. In place of var v = this.value; change it to var v = this.value.replace(/,/g,''); . Numbers such as 21,345,67.800 are too considered.

Does anyone know how this checks for numbers? Does it use keycodes or regular expressions? Important if you consider different keyboard layouts.

$(document).on('keyup keypress', '#somethingSomething', function(){ 	var aValue = $(this).val(); 	if($.isNumeric(aValue) === false){ 		$(this).val(aValue.slice(0,-1)); 	} });

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 44

jQuery.isNumeric( value )
$.isNumeric( "-10" );     // true
$.isNumeric( 16 );        // true
$.isNumeric( 0xFF );      // true
$.isNumeric( "0xFF" );    // true
$.isNumeric( "8e5" );     // true (exponential notation string)
$.isNumeric( 3.1415 );    // true
$.isNumeric( +10 );       // true
$.isNumeric( 0144 );      // true (octal integer literal)
$.isNumeric( "" );        // false
$.isNumeric({});          // false (empty object)
$.isNumeric( NaN );       // false
$.isNumeric( null );      // false
$.isNumeric( true );      // false
$.isNumeric( Infinity );  // false
$.isNumeric( undefined ); // false

Here is an example of how to tie the isNumeric() in with the event listener

$(document).on('keyup', '.numeric-only', function(event) {
   var v = this.value;
   if($.isNumeric(v) === false) {
        //chop off the last char entered
        this.value = this.value.slice(0,-1);
   }
});

+1 for no plugins. I would like to add a slight change to allow thousands separetor. In place of var v = this.value; change it to var v = this.value.replace(/,/g,''); . Numbers such as 21,345,67.800 are too considered.

Does anyone know how this checks for numbers? Does it use keycodes or regular expressions? Important if you consider different keyboard layouts.

$(document).on('keyup keypress', '#somethingSomething', function(){ 	var aValue = $(this).val(); 	if($.isNumeric(aValue) === false){ 		$(this).val(aValue.slice(0,-1)); 	} });

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 14

Below is what I use to literally block the keystrokes. This only allows numbers 0-9 and a decimal point. Easy to implement, not a lot of code, and works like a charm:

<script>
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    } else {
        return true;
    }      
}
</script>

<input value="" onkeypress="return isNumberKey(event)">

If anyone is wondering- you can restrict decimals by removing charCode != 46 from the if statement. Great answer!

This is a bad solution because it doesn't take backspace, arrows, control keys and other necessary keystrokes into account.

I just posted a solution which is similar to this, but also handles backspace, arrows and uses no hard-coded key codes. Check it out here: stackoverflow.com/a/23468513/838608

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 14

Below is what I use to literally block the keystrokes. This only allows numbers 0-9 and a decimal point. Easy to implement, not a lot of code, and works like a charm:

<script>
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    } else {
        return true;
    }      
}
</script>

<input value="" onkeypress="return isNumberKey(event)">

If anyone is wondering- you can restrict decimals by removing charCode != 46 from the if statement. Great answer!

This is a bad solution because it doesn't take backspace, arrows, control keys and other necessary keystrokes into account.

I just posted a solution which is similar to this, but also handles backspace, arrows and uses no hard-coded key codes. Check it out here: stackoverflow.com/a/23468513/838608

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 33

The numeric() plugin mentioned above, doesn't work in Opera (you can't backspace, delete or even use the back or forward keys).

The code below in both JQuery or Javascript will work perfectly (and it's only two lines).

$(document).ready(function() {
    $('.key-numeric').keypress(function(e) {
            var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
            if (verified) {e.preventDefault();}
    });
});
function isNumeric(e)
{
    var keynum = (!window.event) ? e.which : e.keyCode;
    return !((keynum == 8 || keynum == undefined || e.which == 0) ? null : String.fromCharCode(keynum).match(/[^0-9]/));
}

Of course this is for pure numeric input (plus backspace, delete, forward/back keys) only but can easily be changed to include points and minus characters.

This a correct answer. Thanks!

numpad is also not allowed

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 33

The numeric() plugin mentioned above, doesn't work in Opera (you can't backspace, delete or even use the back or forward keys).

The code below in both JQuery or Javascript will work perfectly (and it's only two lines).

$(document).ready(function() {
    $('.key-numeric').keypress(function(e) {
            var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
            if (verified) {e.preventDefault();}
    });
});
function isNumeric(e)
{
    var keynum = (!window.event) ? e.which : e.keyCode;
    return !((keynum == 8 || keynum == undefined || e.which == 0) ? null : String.fromCharCode(keynum).match(/[^0-9]/));
}

Of course this is for pure numeric input (plus backspace, delete, forward/back keys) only but can easily be changed to include points and minus characters.

This a correct answer. Thanks!

numpad is also not allowed

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 24

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});

I like this solution the best.

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 24

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});

I like this solution the best.

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 9

As a slight improvement to this suggestion, you can use the Validation plugin with its number(), digits, and range methods. For example, the following ensures you get a positive integer between 0 and 50:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true,
      digits: true,
      range : [0, 50]
    }
  }
});

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 9

As a slight improvement to this suggestion, you can use the Validation plugin with its number(), digits, and range methods. For example, the following ensures you get a positive integer between 0 and 50:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true,
      digits: true,
      range : [0, 50]
    }
  }
});

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 16

No need for the long code for number input restriction just try this code.

onload =function(){ 
  var ele = document.querySelectorAll('.number-only')[0];
  ele.onkeypress = function(e) {
     if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
        return false;
  }
  ele.onpaste = function(e){
     e.preventDefault();
  }
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
$(function(){

  $('.number-only').keypress(function(e) {
	if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
  })
  .on("cut copy paste",function(e){
	e.preventDefault();
  });

});

The above answers are for most common use case - validating input as a number.

But below is the code snippet for special use cases

  • Showing the invalid keystroke before removing it.
$(function(){
      
  $('.number-only').keyup(function(e) {
        if(this.value!='-')
          while(isNaN(this.value))
            this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
                                   .split('').reverse().join('');
    })
    .on("cut copy paste",function(e){
    	e.preventDefault();
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric
Rectangle 27 16

No need for the long code for number input restriction just try this code.

onload =function(){ 
  var ele = document.querySelectorAll('.number-only')[0];
  ele.onkeypress = function(e) {
     if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
        return false;
  }
  ele.onpaste = function(e){
     e.preventDefault();
  }
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
$(function(){

  $('.number-only').keypress(function(e) {
	if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
  })
  .on("cut copy paste",function(e){
	e.preventDefault();
  });

});

The above answers are for most common use case - validating input as a number.

But below is the code snippet for special use cases

  • Showing the invalid keystroke before removing it.
$(function(){
      
  $('.number-only').keyup(function(e) {
        if(this.value!='-')
          while(isNaN(this.value))
            this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
                                   .split('').reverse().join('');
    })
    .on("cut copy paste",function(e){
    	e.preventDefault();
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

validation - jQuery: what is the best way to restrict "number"-only in...

jquery validation isnumeric