JavaScript

JS表单验证的方法及示例分享

下文笔者讲述JavaScript中表单验证的方法及示例简介说明,如下所示

表单及验证简介

表单是交互页面的基础,所有的交互页面都是采用表单进行交互操作
  如:
   网页上的用户名、手机号、密码等表单
  但当我们填写这些表单信息时,我们需对其进行相应的验证操作
    如:手机号必须符合规范,密码必须符合规范
	   那么如何使用JS达到这一验证的目的呢?
	 下文笔者将一一道来,如下所示
表单验证的实现思路:
    1.使用Javascript获取页面DOM对象的方法获取html元素值
    2.使用JS语法中判空或正则表达式进行验证操作
	3.将不符合规则的元素值输出,并给用户相应的提示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>linux28.com -- JavaScript</title>
    <style>
        .error{
            color: red;
        }
        label{
            display: inline-block;
            width: 70px;
            text-align: right;
        }
    </style>
</head>
<body>
    <form onsubmit="return validateForm()" action="" method="post">
        <fieldset>
            <legend>注册:</legend>
            <div class="row">
                <label>用户名:</label>
                <input type="text" name="name">
                <span class="error" id="nameErr"></span>
            </div>
            <div class="row">
                <label>密码:</label>
                <input type="password" name="pwd">
                <span class="error" id="pwdErr"></span>
            </div>
            <div class="row">
                <label>Email:</label>
                <input type="text" name="email">
                <span class="error" id="emailErr"></span>
            </div>
            <div class="row">
                <label>手机号:</label>
                <input type="text" name="mobile" maxlength="11">
                <span class="error" id="mobileErr"></span>
            </div>
            <div class="row">
                <label>验证码:</label>
                <input type="text" name="captcha" maxlength="4"><span id="captcha" onclick="getCaptcha()"></span>
                <span class="error" id="captchaErr"></span>
            </div>
            <div class="row">
                <input type="submit" value="注册">
            </div>
        </fieldset>
    </form>
    <script>
        var captcha = getCaptcha(); // 生成验证码
        // 清空 input 标签后的提示信息
        var tags = document.getElementsByTagName('input');
        for (var i = 0; i < tags.length; i++) {
            tags[i].onchange = function(){
                var idname = this.name + "Err";
                document.getElementById(idname).innerHTML = '';
            }
        }
        // 显示错误消息
        function printError(elemId, hintMsg) {
            document.getElementById(elemId).innerHTML = hintMsg;
        }
        // 验证表单数据
        function validateForm() {
            // 获取表单元素的值
            var name = document.querySelector("input[name='name']").value;
            var pwd = document.querySelector("input[name='pwd']").value;
            var email = document.querySelector("input[name='email']").value;
            var mobile = document.querySelector("input[name='mobile']").value;
            var captcha = document.querySelector("input[name='captcha']").value;
                  
            if(name == "" || name == null){
                printError("nameErr", "用户名不能为空");
                return false;
            }
            if(pwd == "" || pwd == null){
                printError("pwdErr", "密码不能为空");
                return false;
            }
            if(email == "" || email == null){
                printError("emailErr", "邮箱不能为空");
                return false;
            }
            if(mobile == "" || mobile == null){
                printError("mobileErr", "手机号不能为空");
                return false;
            }
            if(captcha == "" || captcha == null){
                printError("captchaErr", "验证码不能为空");
                return false;
            }
        }
        // 获取验证码
        function getCaptcha(){
            var cap = Math.floor(Math.random()*10000).toString();
            if(cap.length != 4) cap += "0";
            captcha = cap;
            document.getElementById("captcha").innerHTML = cap;
        }
    </script>
</body>
</html>
JavaScript数据验证的示例-1

数据格式验证

验证邮箱
验证手机号码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> linux28.com -- JavaScript</title>
    <style>
        .error{
            color: red;
        }
        label{
            display: inline-block;
            width: 70px;
            text-align: right;
        }
    </style>
</head>
<body>
    <form onsubmit="return validateForm()" action="" method="post">
        <fieldset>
            <legend>注册:</legend>
            <div class="row">
                <label>用户名:</label>
                <input type="text" name="name">
                <span class="error" id="nameErr"></span>
            </div>
            <div class="row">
                <label>密码:</label>
                <input type="password" name="pwd">
                <span class="error" id="pwdErr"></span>
            </div>
            <div class="row">
                <label>Email:</label>
                <input type="text" name="email">
                <span class="error" id="emailErr"></span>
            </div>
            <div class="row">
                <label>手机号:</label>
                <input type="text" name="mobile" maxlength="11">
                <span class="error" id="mobileErr"></span>
            </div>
            <div class="row">
                <label>验证码:</label>
                <input type="text" name="captcha" maxlength="4"><span id="captcha" onclick="getCaptcha()"></span>
                <span class="error" id="captchaErr"></span>
            </div>
            <div class="row">
                <input type="submit" value="注册">
            </div>
        </fieldset>
    </form>
    <script>
        var capCode = getCaptcha(); // 生成验证码
        console.log(capCode);
        // 清空 input 标签后的提示信息
        var tags = document.getElementsByTagName('input');
        for (var i = 0; i < tags.length; i++) {
            tags[i].onchange = function(){
                var idname = this.name + "Err";
                document.getElementById(idname).innerHTML = '';
            }
        }
        // 显示错误消息
        function printError(elemId, hintMsg) {
            document.getElementById(elemId).innerHTML = hintMsg;
        }
        // 验证表单数据
        function validateForm() {
            // 获取表单元素的值
            var name = document.querySelector("input[name='name']").value;
            var pwd = document.querySelector("input[name='pwd']").value;
            var email = document.querySelector("input[name='email']").value;
            var mobile = document.querySelector("input[name='mobile']").value;
            var captcha = document.querySelector("input[name='captcha']").value;
                  
            if(name == "" || name == null){
                printError("nameErr", "用户名不能为空");
                return false;
            }
            if(pwd == "" || pwd == null){
                printError("pwdErr", "密码不能为空");
                return false;
            }
            if(email == "" || email == null){
                printError("emailErr", "邮箱不能为空");
                return false;
            } else {
                var regex = /^\S+@\S+\.\S+$/;
                if(regex.test(email) === false) {
                    printError("emailErr", "请输入正确的邮箱地址");
                    return false;
                }
            }
            if(mobile == "" || mobile == null){
                printError("mobileErr", "手机号不能为空");
                return false;
            } else {
                var regex = /^[1]\d{10}$/;
                if(regex.test(mobile) === false) {
                    printError("mobileErr", "您输入的手机号码有误");
                    return false;
                }
            }
            if(captcha == "" || captcha == null){
                printError("captchaErr", "验证码不能为空");
                return false;
            } else {
                console.log(capCode);
                console.log(captcha);
                if(capCode != captcha){
                    printError("captchaErr", "验证码有误");
                    return false;
                }
            }
        }
        // 获取验证码
        function getCaptcha(){
            var cap = Math.floor(Math.random()*10000).toString();
            if(cap.length != 4) cap += "0";
            document.getElementById("captcha").innerHTML = cap;
            return capCode = cap;
        }
    </script>
</body>
</html>
JavaScript正则表达式验证的示例分享