Check if only the text field contains only numbers

How to check if only a text field contains only numbers?

While googling I came across this. But I'm wondering if isNumeric can be used for this purpose, or if there are simpler ways to check if the text field has a numerical value.

 var query = $('#myText').val(); if (parseFloat(query) == NaN) { alert("query is a string"); } else { alert("query is numeric"); } 
+6
source share
5 answers

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

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

REGEX:

  • / : regex delimiters
  • ^ : starts with
  • \d : Any number
  • + : one or more previous characters
  • $ : End

Regular Expression 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+" /> 
+21
source

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"> 
+3
source

There are many ways you can use isNaN

  isNaN(VALUE); 

You can also use regEx to check for numeric values.

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

Jquery provides a general utility method for handling this. handles numeric / float / hex

 $.isNumeric( value ) 

Try it: fiddle

+1
source

You can match the value of the text field with numeric regression to check if it contains only numbers or not, for example, below the code ...

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

Source: https://habr.com/ru/post/987497/


All Articles