Omnipresent Omnipresent - 1 year ago 72
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.

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download