Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
384 views
Welcome To Ask or Share your Answers For Others

1 Answer

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');
   ...
}    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...