Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
}
like image 307
Becky Avatar asked May 19 '15 10:05

Becky


People also ask

How can I tell if a TextBox contains only numbers?

Switch to design view from markup view. Now click on design view and press Ctrl + Alt + X . From the toolbox that opens click on Validation and drag a compare validator near your TextBox . Right click on the compare validator and choose properties, now locate ErrorMessage and write "Alert: Type only Number".

How can check TextBox value is numeric 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.


1 Answers

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+" />
like image 189
Tushar Avatar answered Sep 21 '22 13:09

Tushar