邮箱:
手机:
" />

小言_互联网的博客

JavaScript表单信息验证案例——使用正则

237人阅读  评论(0)

展示

设计

首先建立我们的输入框

QQ号:<input type="text" id="txtQQ"><span></span><br>
邮箱:<input type="text" id="txtEMail"><span></span><br>
手机:<input type="text" id="txtPhone"><span></span><br>
生日:<input type="text" id="txtBirthday"><span></span><br>
姓名:<input type="text" id="txtName"><span></span><br>

建好之后就可以进行对输入的数据进行获取判断了

例如用document.getElementById("txtQQ")获取文本框,在设计一个函数进行判断

//获取文本框
var txtQQ = document.getElementById("txtQQ");
var txtEMail = document.getElementById("txtEMail");
var txtPhone = document.getElementById("txtPhone");
var txtBirthday = document.getElementById("txtBirthday");
var txtName = document.getElementById("txtName");

// qq
txtQQ.onblur = function () {
   
  //获取当前文本框对应的span
  var span = this.nextElementSibling;
  var reg = /^\d{5,12}$/;
  //判断验证是否成功
  if(!reg.test(this.value) ){
   
    //验证不成功
    span.innerText = "请输入正确的QQ号";
    span.style.color = "red";
  }else{
   
    //验证成功
    span.innerText = "";
    span.style.color = "";
  }
};

//txtEMail
txtEMail.onblur = function () {
   
  //获取当前文本框对应的span
  var span = this.nextElementSibling;
  var reg = /^\w+@\w+\.\w+(\.\w+)?$/;
  //判断验证是否成功
  if(!reg.test(this.value) ){
   
    //验证不成功
    span.innerText = "请输入正确的EMail地址";
    span.style.color = "red";
  }else{
   
    //验证成功
    span.innerText = "";
    span.style.color = "";
  }
};
/*

省略验证手机等方法

*/

但是这样写会造成代码冗余,我们可以将表单验证部分封装成一个功能函数,例如:

var regBirthday = /^\d{4}-\d{1,2}-\d{1,2}$/;
addCheck(txtBirthday, regBirthday, "请输入正确的出生日期");
//给文本框添加验证
function addCheck(element, reg, tip) {
   
  element.onblur = function () {
   
    //获取当前文本框对应的span
    var span = this.nextElementSibling;
    //判断验证是否成功
    if(!reg.test(this.value) ){
   
      //验证不成功
      span.innerText = tip;
      span.style.color = "red";
    }else{
   
      //验证成功
      span.innerText = "";
      span.style.color = "";
    }
  };
}

通过给元素增加自定义验证属性对表单进行验证:

<form id="frm">
  QQ号:<input type="text" name="txtQQ" data-rule="qq"><span></span><br>
  邮箱:<input type="text" name="txtEMail" data-rule="email"><span></span><br>
  手机:<input type="text" name="txtPhone" data-rule="phone"><span></span><br>
  生日:<input type="text" name="txtBirthday" data-rule="date"><span></span><br>
  姓名:<input type="text" name="txtName" data-rule="cn"><span></span><br>
</form>
// 所有的验证规则
var rules = [
  {
   
    name: 'qq',
    reg: /^\d{5,12}$/,
    tip: "请输入正确的QQ"
  },
  {
   
    name: 'email',
    reg: /^\w+@\w+\.\w+(\.\w+)?$/,
    tip: "请输入正确的邮箱地址"
  },
  {
   
    name: 'phone',
    reg: /^\d{11}$/,
    tip: "请输入正确的手机号码"
  },
  {
   
    name: 'date',
    reg: /^\d{4}-\d{1,2}-\d{1,2}$/,
    tip: "请输入正确的出生日期"
  },
  {
   
    name: 'cn',
    reg: /^[\u4e00-\u9fa5]{2,4}$/,
    tip: "请输入正确的姓名"
  }];

addCheck('frm');


//给文本框添加验证
function addCheck(formId) {
   
  var i = 0,
      len = 0,
      frm =document.getElementById(formId);
  len = frm.children.length;
  for (; i < len; i++) {
   
    var element = frm.children[i];
    // 表单元素中有name属性的元素添加验证
    if (element.name) {
   
      element.onblur = function () {
   
        // 使用dataset获取data-自定义属性的值
        var ruleName = this.dataset.rule;
        var rule =getRuleByRuleName(rules, ruleName);

        var span = this.nextElementSibling;
        //判断验证是否成功
        if(!rule.reg.test(this.value) ){
   
          //验证不成功
          span.innerText = rule.tip;
          span.style.color = "red";
        }else{
   
          //验证成功
          span.innerText = "";
          span.style.color = "";
        }
      }
    }
  }
}

// 根据规则的名称获取规则对象
function getRuleByRuleName(rules, ruleName) {
   
  var i = 0,
      len = rules.length;
  var rule = null;
  for (; i < len; i++) {
   
    if (rules[i].name == ruleName) {
   
      rule = rules[i];
      break;
    }
  }
  return rule;
}

完整代码

简约版

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>title</title>
  <style>
    .fei {
    
      position: absolute;
      top: 100px;
      left: 100px;
    }
  </style>
</head>

<body>
  <form class="fei" id="frm">
    QQ号:<input type="text" name="txtQQ" data-rule="qq"><span></span><br>
    邮箱:<input type="text" name="txtEMail" data-rule="email"><span></span><br>
    手机:<input type="text" name="txtPhone" data-rule="phone"><span></span><br>
    生日:<input type="text" name="txtBirthday" data-rule="date"><span></span><br>
    姓名:<input type="text" name="txtName" data-rule="cn"><span></span><br>
  </form>
  <script>
    // 所有的验证规则
    var rules = [
      {
    
        name: 'qq',
        reg: /^\d{5,12}$/,
        tip: "请输入正确的QQ"
      },
      {
    
        name: 'email',
        reg: /^\w+@\w+\.\w+(\.\w+)?$/,
        tip: "请输入正确的邮箱地址"
      },
      {
    
        name: 'phone',
        reg: /^\d{11}$/,
        tip: "请输入正确的手机号码"
      },
      {
    
        name: 'date',
        reg: /^\d{4}-\d{1,2}-\d{1,2}$/,
        tip: "请输入正确的出生日期"
      },
      {
    
        name: 'cn',
        reg: /^[\u4e00-\u9fa5]{2,4}$/,
        tip: "请输入正确的姓名"
      }];

    addCheck('frm');


    //给文本框添加验证
    function addCheck(formId) {
    
      var i = 0,
        len = 0,
        frm = document.getElementById(formId);
      len = frm.children.length;
      for (; i < len; i++) {
    
        var element = frm.children[i];
        // 表单元素中有name属性的元素添加验证
        if (element.name) {
    
          element.onblur = function () {
    
            // 使用dataset获取data-自定义属性的值
            var ruleName = this.dataset.rule;
            var rule = getRuleByRuleName(rules, ruleName);

            var span = this.nextElementSibling;
            //判断验证是否成功
            if (!rule.reg.test(this.value)) {
    
              //验证不成功
              span.innerText = rule.tip;
              span.style.color = "red";
            } else {
    
              //验证成功
              span.innerText = "";
              span.style.color = "";
            }
          }
        }
      }
    }

    // 根据规则的名称获取规则对象
    function getRuleByRuleName(rules, ruleName) {
    
      var i = 0,
        len = rules.length;
      var rule = null;
      for (; i < len; i++) {
    
        if (rules[i].name == ruleName) {
    
          rule = rules[i];
          break;
        }
      }
      return rule;
    }
  </script>
</body>

</html>

豪华版

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    body {
    
      background: #ccc;
    }

    label {
    
      width: 40px;
      display: inline-block;
    }

    span {
    
      color: red;
    }

    .container {
    
      margin: 100px auto;
      width: 400px;
      padding: 50px;
      line-height: 40px;
      border: 1px solid #999;
      background: #efefef;
    }

    span {
    
      margin-left: 30px;
      font-size: 12px;
    }

    .wrong {
    
      color: red
    }

    .right {
    
      color: green;
    }

    .defau {
    
      width: 200px;
      height: 20px;
    }

    .de1 {
    
      background-position: 0 -20px;
    }
  </style>

</head>

<body>
  <div class="container" id="dv">
    <label for="qq">Q Q</label><input type="text" id="qq"><span></span><br />
    <label>手机</label><input type="text" id="phone"><span></span><br />
    <label>邮箱</label><input type="text" id="e-mail"><span></span><br />
    <label>座机</label><input type="text" id="telephone"><span></span><br />
    <label>姓名</label><input type="text" id="fullName"><span></span><br />
  </div>
  <script>
    function my$(id) {
    
      return document.getElementById(id);
    }

    //qq的
    checkInput(my$("qq"), /^\d{5,11}$/);
    //手机
    checkInput(my$("phone"), /^\d{11}$/);
    //邮箱
    checkInput(my$("e-mail"), /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/);
    //座机号码
    checkInput(my$("telephone"), /^\d{3,4}[-]\d{7,8}$/);
    //中文名字
    checkInput(my$("fullName"), /^[\u4e00-\u9fa5]{2,6}$/);
    //给我文本框,给我这个文本框相应的正则表达式,我把结果显示出来
    //通过正则表达式验证当前的文本框是否匹配并显示结果
    function checkInput(input, reg) {
    
      //文本框注册失去焦点的事件
      input.onblur = function () {
    
        if (reg.test(this.value)) {
    
          this.nextElementSibling.innerText = "正确了";
          this.nextElementSibling.style.color = "green";
        } else {
    
          this.nextElementSibling.innerText = "错了吧,不要乱搞!";
          this.nextElementSibling.style.color = "red";
        }
      };
    }

  </script>

</body>

</html>

转载:https://blog.csdn.net/weixin_45525272/article/details/116398380
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场