JS同时验证固话和手机号正则表达式,验证规则: 1:当input框没有填写号码的时候,input为空,可通过验证 2:当手机号码填写正确的时候,可通过验证 3:当座机号码填写正确的时候,可通过验证 如果不通过,则出现提示信息,提示输入正确的手机号码座机号码。
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="phone" ></input>
<button type="button" class="btn blue" id="addBtn">保存</button>
<!-- 弹框 -->
<script src="https://cdn.bootcss.com/layer/2.2/layer.js"></script>
<script src="https://cdn.bootcss.com/layer/2.2/extend/layer.ext.js"></script>
<script type="text/javascript">
$("#addBtn").on("click", function() {
var $phone_num = $("#phone").val();
var reg01 = /^(0|86|17951)?(13[0-9]|15[012356789]|17[01678]|18[0-9]|14[57])[0-9]{8}$/;
var reg02 = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
if(reg01.test($phone_num) || reg02.test($phone_num) || $("#phone").val()=="") {
console.log("手机号或座机号填写正确")
} else {
layer.msg('请填写正确的号码', {
icon : 5,
time : 1000
});
return;
}
})
</script>
</body>
</html>
也可以这样写
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="phone" ></input>
<button type="button" class="btn blue" id="addBtn">保存</button>
<!-- 弹框 -->
<script src="https://cdn.bootcss.com/layer/2.2/layer.js"></script>
<script src="https://cdn.bootcss.com/layer/2.2/extend/layer.ext.js"></script>
<script type="text/javascript">
$("#addBtn").on("click", function() {
var $phone_num = $("#phone").val();
var reg01 = /^(0|86|17951)?(13[0-9]|15[012356789]|17[01678]|18[0-9]|14[57])[0-9]{8}$/;
var reg02 = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
if(!reg01.test($phone_num) && !reg02.test($phone_num) && !$("#phone").val()=="") {
layer.msg('请填写正确的号码', {
icon : 5,
time : 1000
});
} else {
console.log("手机号或座机号填写正确")
}
})
</script>
</body>
</html>