首页 > 解决方案 > 使用具有相同功能(如按键)的正则表达式验证 javascript 中的电话号码

问题描述

使用具有相同功能(如按键)的正则表达式验证 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();
            });

标签: javascriptjqueryvalidation

解决方案


这是一个快速有效的示例。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>

推荐阅读