Check if a textbox contains numbers only

后端 未结 5 1743
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 06:38

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 t

相关标签:
5条回答
  • 2020-12-10 07:10

    There're many ways, you can use isNaN

     isNaN(VALUE);
    

    You can also use regEx to verify numeric values.

    console.log(/^\d+$/.test(VALUE));
    
    0 讨论(0)
  • 2020-12-10 07:17

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

    $.isNumeric( value )
    

    Try: fiddle

    0 讨论(0)
  • 2020-12-10 07:22

    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:

    Demo


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

    <input type="number" pattern="\d+" />
    
    0 讨论(0)
  • 2020-12-10 07:29

    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">
    
    0 讨论(0)
  • 2020-12-10 07:29

    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
    }
    
    0 讨论(0)
提交回复
热议问题