Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if number entered is a digit in jquery

I have a simple textbox in which users enter number.
Does jQuery have a isDigit 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.

like image 370
Omnipresent Avatar asked Aug 13 '09 15:08

Omnipresent


People also ask

Is number validation in jQuery?

The jQuery $. isNumeric() method is used to check whether the entered number is numeric or not. $. isNumeric() method: It is used to check whether the given argument is a numeric value or not.

How check textbox value is numeric or not in jQuery?

jQuery isNumeric() method The isNumeric() method in jQuery is used to determine whether the passed argument is a numeric value or not. The isNumeric() method returns a Boolean value. If the given argument is a numeric value, the method returns true; otherwise, it returns false.


2 Answers

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');    ... }     
like image 50
karim79 Avatar answered Oct 15 '22 00:10

karim79


Forget regular expressions. JavaScript has a builtin function for this: isNaN():

isNaN(123)           // false isNaN(-1.23)         // false isNaN(5-2)           // false isNaN(0)             // false isNaN("100")         // false isNaN("Hello")       // true isNaN("2005/12/12")  // true 

Just call it like so:

if (isNaN( $("#whatever").val() )) {     // It isn't a number } else {     // It is a number } 
like image 22
Plutor Avatar answered Oct 15 '22 01:10

Plutor