Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  74] [ 7]  / answers: 1 / hits: 31944  / 9 Years ago, tue, may 19, 2015, 12:00:00

How to check if a textbox contains numbers only?



While googling I came across this. But I'm wondering if isNumeric can be used for this purpose or if there are more simpler ways of checking if a textbox has a numeric value.



var query = $('#myText').val();
if (parseFloat(query) == NaN) {
alert(query is a string);
} else {
alert(query is numeric);
}

More From » jquery

 Answers
18

You can check if the user has entered only numbers using change event on input and regex.



$(document).ready(function() {
$('#myText').on('change', function() {
if (/^d+$/.test($(this).val())) {
// Contain numbers only
} else {
// Contain other characters also
}
})
});


REGEX:




  1. /: Delimiters of regex

  2. ^: Starts with

  3. d: Any digit

  4. +: One or more of the preceding characters

  5. $: End



Regex Visualization:



enter



Demo






If you want to allow only numbers, you can use input-number and pattern



<input type=number pattern=d+ />

[#66551] Saturday, May 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carrington

Total Points: 674
Total Questions: 90
Total Answers: 108

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;