javascript - 使用具有相同功能(如按键)的正则表达式验证 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();
});
解决方案
这是一个快速有效的示例。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>
推荐阅读
- node.js - 让我的 Discord 机器人读取网页内容的简单方法?
- jmeter - Jmeter - 获取响应代码:403 响应消息:禁止错误
- javascript - 尝试从 JSON.stringified 对象创建 blob 时出错
- java - 为什么当我在 Android Studio 中更改元素 ID 时,我的应用程序设计未配置?
- ios - 如何使用 ARKit 和 SceneKit 录制屏幕?
- flutter - 在构建方法之外无法调用useContext颤振钩子的真正用途是什么?
- php - 在mysql中搜索日期
- laravel - 关系总和的范围模型
- c# - 在 ASP.Net 集成测试中阻止 SQL Server 连接
- swift - SwiftUI Multiplatform 为 macOS 生成“Cannot find type 'MyClass' in scope”