簡體   English   中英

使用具有相同功能(如按鍵)的正則表達式驗證javascript中的電話號碼

[英]Validate phone number in javascript using regular expression with same functionality like keypress

使用具有相同功能(如按鍵)的正則表達式驗證javascript中的電話號碼

$('#phone').keypress(function(e) {
                var a = [];
                var k = e.which;

                for (i = 48; i < 58; i++)
                    a.push(i);

                if (!(a.indexOf(k)>=0))
                    e.preventDefault();
            });

這是一個快速有效的示例。 JS小提琴

<style>
    .invalid {
        border: 2px solid red; 
    }
</style>

<input id="input" type="text" />

<script>
    // save reference to input
    const input = $('#input');

    // save regex to check against
    const regex = new RegExp('^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$', 'im');

    // on keypress, get user input
    // strip non-digits (1-2 => 12 | 5.6 => 56)
    // run regex test and add/remove class to show validation
    function checkPhoneNumber(){
        const user_input = input.val().replace(/\D/g, ""); // replace any non-digits with nothing
        const valid_phone = regex.test(user_input);
        if (valid_phone){
            input.removeClass('invalid');
        } else {
            input.addClass('invalid');
        }
    }

    // attach listener with function
    input.on('keyup', checkPhoneNumber);
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM