JavaScript可以验证手机号码吗?怎么编写JS代码实现设置?

济南云服务器 2026年5月18日05:09:09JavaScriptJavaScript可以验证手机号码吗?怎么编写JS代码实现设置?已关闭评论41阅读模式

当网站需要用户注册网站会员时,一般会遇到验证手机号码是否正确的需求,那么,怎么通过编写JavaScript编程语言,来解决该需求呢?接下来,济南网站建设小编就来为大家分享一个通过编写JavaScript代码来实现该需求的小案例,希望对有需要的朋友,有所帮助

关键代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>JS手机号验证</title>
    <style>
        div{margin:50px;}
        input{padding:8px;width:250px;font-size:15px;}
        button{padding:8px 15px;background:#1677ff;color:#fff;border:none;border-radius:4px;cursor:pointer;margin-left:10px;}
        .msg{margin-top:15px;font-size:14px;}
        .success{color:green;}
        .error{color:red;}
    </style>
</head>
<body>
    <div>
        <input type="text" id="tel" placeholder="请输入手机号码">
        <button onclick="checkPhone()">立即验证</button>
        <div class="msg" id="tips"></div>
    </div>

    <script>
        function checkPhone(){
            // 获取输入框内容
            let phone = document.getElementById('tel').value.trim();
            let tip = document.getElementById('tips');
            // 手机号正则
            let reg = /^1[3-9]\d{9}$/;

            if(phone === ''){
                tip.className = 'msg error';
                tip.innerText = '手机号不能为空哦';
                return;
            }
            if(reg.test(phone)){
                tip.className = 'msg success';
                tip.innerText = '手机号码格式正确';
            }else{
                tip.className = 'msg error';
                tip.innerText = '请输入合法的11位手机号码';
            }
        }
    </script>
</body>
</html>

济南云服务器
  • 本文由 发表于 2026年5月18日05:09:09
  • 转载请务必保留本文链接:http://news.hcsw666.com/2759