Check if a textbox contains numbers only

后端 未结 5 1809
佛祖请我去吃肉
佛祖请我去吃肉 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: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

    
    

提交回复
热议问题