Omnipresent Omnipresent - 3 months ago 4x
Javascript Question

checking if number entered is a digit in jquery

I have a simple

in which users enter number.

Does jQuery have a
function that will allow me to show an alert box if users enter something other than digits?

The field can have decimal points as well.


I would suggest using regexes:

var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;

var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
   alert('I am a number');

Or with a single regex as per @Platinum Azure's suggestion:

var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
   alert('I am a number');