Becky
Becky

Reputation: 5605

Check if a textbox contains numbers only

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");
}

Upvotes: 8

Views: 33243

Answers (5)

Tushar
Tushar

Reputation: 87233

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 image description here

Demo


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

<input type="number" pattern="\d+" />

Upvotes: 27

Amit G
Amit G

Reputation: 2423

Jquery provides generic util method to handle this. handles numeric/float/hex

$.isNumeric( value )

Try: fiddle

Upvotes: 2

Bellash
Bellash

Reputation: 8204

using pure JS regular expression

 var query = document.getElementById('myText').value;
 var isNumeric=query.match(/^\d+$/);
  if(isNumeric){/*...*/}else{/*...*/}

or using html5 control

 <input type="number" name="quantity" min="1" max="5">

Upvotes: 4

Mox Shah
Mox Shah

Reputation: 3015

There're many ways, you can use isNaN

 isNaN(VALUE);

You can also use regEx to verify numeric values.

console.log(/^\d+$/.test(VALUE));

Upvotes: 2

Dipesh Rana
Dipesh Rana

Reputation: 367

You can match the value of text box against the numeric regression to check if it contains numbers only or not, Like below code...

if($('#myText').val().match(/^\d+$/)){
// Your code here
}

Upvotes: 0

Related Questions