使用具有相同功能(如按键)的正则表达式验证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();
});
答案 0 :(得分:0)
这是一个快速有效的示例。 JS Fiddle
<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>