亲宝软件园·资讯

展开

JavaScript表单验证的两种实现方法

zuncle 人气:0

本文实例为大家分享了js表单验证的实现方法,供大家参考,具体内容如下

第一种:js表单验证

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>注册-个人用户</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <script src="//cdn.bootcss.com/jquery/3.0.0-beta1/jquery.js"></script>
  <style>
    body {
      font-family: Arial, "宋体", Lucida, Verdana, Helvetica, sans-serif;
      font-size: 12px;
      color: #333;
      line-height: 150%;
      background: #f2f2f2;
    }

    .hide{display:none;}

    .focus,.error {
      color: #e4393c;
      line-height: 36px;
      height: 36px;
      position: absolute;
      top: 0px;

      width: 260px;
      padding: 0 5px;
      background: #FFEBEB;
      border: 1px solid #ffbdbe;
    }

    .error span,.focus span {
      padding: 5px 0;
      line-height: 13px;
      display: block;
    }

    .focus {
      color: #666;
      width: 260px;;
      line-height: 36px;
      background: #f7f7f7;
      border: 1px solid #dddddd;
    }

    .regist {
      width: 990px;
      padding: 0;
      margin: 0 auto;
      zoom: 1;
    }


    .mc {
      padding: 30px 0 20px;
      border: solid #dddddd; border-width : 0px 1px 1px;
      background: #FFF;
      overflow: hidden;
      zoom: 1;
      border-width: 0px 1px 1px;
    }

    .form {
      float: left;
      width: 750px;
      font-size: 12px;
    }

    .form label,.form input,.form select,.form textarea,.form button,.form .label {
      float: left;
      font-size: 12px;
    }

    .item {
      padding-top: 9px;
      height: 60px;
      line-height: 34px;
      position: relative;
      z-index: 1;
    }

    .label {
      float: left;
      width: 190px;
      text-align: right;
      font-size: 14px;
      color: #999;
      padding-right: 10px;
    }

    .input {
      float: left;
      position: relative;
      width: 270px;
      overflow: visible;
    }

    .text {
      float: none;
      width: 275px;
      height: 37px;
      line-height: 32px;
      border: 1px solid #cccccc;
      font-size: 14px;
      font-family: arial, "宋体";
      overflow: hidden;
    }

  </style>
</head>
<body>
  <div class="regist"> 
    <div class="mc">
      <form id="personRegForm" class="form" action="login.html" method="POST" onsubmit="return validateForm();">
        <div class="item">
          <span class="label">用户名:</span>
          <div class="input">
            <input type="text" id="username" name="username" class="text">

            <label id="username_msg" class="hide"></label>
          </div>
        </div>
        <div class="item">
          <span class="label">请设置密码:</span>
          <div class="input">
            <input type="password" id="password" name="password" class="text">

            <label id="pwd_msg" class="hide"></label>
          </div>
        </div>
        <div class="item">
          <span class="label">请确认密码:</span>
          <div class="input">
            <input type="password" id="pwdRepeat" name="pwdRepeat" class="text">

            <label id="pwdRepeat_msg" class="hide"></label>
          </div>
        </div>
        <div class="item">
          <span class="label">验证邮箱:</span>
          <div class="input">
            <input type="text" id="mail" name="mail" class="text">

            <label id="mail_msg" class="hide"></label>
          </div>
        </div>
        <div class="item">
          <span class="label"> </span>
          <input type="submit" class="btn-img" id="registsubmit" value="立即注册" />
        </div>
      </form>
    </div>  
  </div>


   <script>
    window.onload = function(){
      // 1. 用户名
      $("#username").focus(function(){
        /* 获取焦点
        var username_msg = $("#username_msg");
        username_msg.text("4-20位字符,支持英文、数字及'-'、'_'组合");
        username_msg.attr("class","focus");
        */
        elemFocus("username_msg","4-20位字符,支持英文、数字及'-'、'_'组合");

      }).blur(userValidator);
      // 2. 密码
      $("#password").focus(function(){
        elemFocus("pwd_msg","6-20位字符,可使用字母、数字的组合");
      }).blur(pwdValidator);
      // 3. 确认密码
      $("#pwdRepeat").focus(function(){
        elemFocus("pwdRepeat_msg","6-20位字符,可使用字母、数字的组合");
      }).blur(pwdRepeatValidator);
      // 4. Email
      $("#mail").focus(function(){
        elemFocus("mail_msg","完成验证后,可以使用该邮箱登录和找回密码");
      }).blur(emailValidator);
    }

    // 定义函数 - 通用的信息提示
    function elemFocus(eleId,text){
      var ele_msg = $("#"+eleId);
      ele_msg.text(text);
      ele_msg.attr("class","focus");
    }

    // 定义验证用户名的函数
    function userValidator(){
      // 获取用户名输入的值
      var value = $("#username").val();
      // 获取用于显示提示信息的元素
      var username_msg = $("#username_msg");
      // 验证逻辑
      if(value==""||value==null){
        username_msg.text("用户名不能为空");
        username_msg.attr("class","error");
        return false;
      }else if(value.length<4||value.length>20){
        username_msg.text("用户名的长度不正确");
        username_msg.attr("class","error");
        return false;
      }else if(!/^[a-zA-Z0-9-_]{4,20}$/.test(value)){
        username_msg.text("用户名输入不正确");
        username_msg.attr("class","error");
        return false;
      }
      // 验证通过修改正确样式
      if(!username_msg.hasClass("hide")){
        username_msg.text("");
        username_msg.attr("class","hide");
      }
      return true;
    }
    // 定义验证密码的函数
    function pwdValidator(){
      var value = $("#password").val();
      var pwd_msg = $("#pwd_msg");
      if(value==""||value==null){
        pwd_msg.text("密码不能为空");
        pwd_msg.attr("class","error");
        return false;
      }else if(value.length<6||value.length>20){
        pwd_msg.text("密码的长度不正确");
        pwd_msg.attr("class","error");
        return false;
      }else if(!/^[a-zA-Z0-9]{6,20}$/.test(value)){
        pwd_msg.text("密码输入不正确");
        pwd_msg.attr("class","error");
        return false;
      }
      if(!pwd_msg.hasClass("hide")){
        pwd_msg.text("");
        pwd_msg.attr("class","hide");
      }
      return true;
    }
    // 定义确认密码验证的函数
    function pwdRepeatValidator(){
      var value = $("#pwdRepeat").val();
      var pwdRepeat_msg = $("#pwdRepeat_msg");
      var pwd = $("#password").val();
      if(value==""||value==null){
        pwdRepeat_msg.text("密码不能为空");
        pwdRepeat_msg.attr("class","error");
        return false;
      }else if(value.length<6||value.length>20){
        pwdRepeat_msg.text("密码的长度不正确");
        pwdRepeat_msg.attr("class","error");
        return false;
      }else if(!/^[a-zA-Z0-9]{6,20}$/.test(value)){
        pwdRepeat_msg.text("密码输入不正确");
        pwdRepeat_msg.attr("class","error");
        return false;
      }else if(value != pwd){
        pwdRepeat_msg.text("两次密码输入不一致");
        pwdRepeat_msg.attr("class","error");
        return false;
      }
      if(!pwdRepeat_msg.hasClass("hide")){
        pwdRepeat_msg.text("");
        pwdRepeat_msg.attr("class","hide");
      }
      return true;
    }
    // 定义Email验证的函数
    function emailValidator(){
      var value = $("#mail").val();
      var email_msg = $("#mail_msg");
      if(value==""||value==null){
        email_msg.text("Email不能为空");
        email_msg.attr("class","error");
        return false;
      }else if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)){
        email_msg.text("Email格式不正确");
        email_msg.attr("class","error");
        return false;
      }
      if(!email_msg.hasClass("hide")){
        email_msg.text("");
        email_msg.attr("class","hide");
      }
      return true;
    }
    function validateForm(){
      if(!userValidator()||!pwdValidator()||!pwdRepeatValidator()||!emailValidator()){
        return false;
      }
      return true;
    }
  </script>
</body>
</html>

第二种:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }

      form {
        width: 570px;
        height: 300px;
        margin: 100px auto;
      }

      label {
        width: 64px;
        float: left;
        clear: left;
        height: 36px;
        line-height: 36px;
        margin-top: 10px;
      }

      input {
        width: 300px;
        height: 36px;
        line-height: 36px;
        margin-top: 10px;
        text-indent: 8px;
        font-size: 16px;
        font-family: "微软雅黑";
        border: 1px solid #ccc;
        float: left;
      }

      #sub {
        width: 302px;
        height: 40px;
        border: 1px solid #ccc;
        background: #888;
        color: #fff;
        font-size: 18px;
        text-indent: 0;
      }

      .spa {
        height: 36px;
        line-height: 36px;
        width: 204px;
        display: inline-block;
        float: left;
        font-size: 12px;
        color: #BD362F;
        text-indent: 10px;
        margin-top: 10px;
      }
    </style>
  </head>

  <body>
    <form action="" method="post">
      <label id="name">姓 名:</label><input type="text" name="username" id="username" value="" placeholder="请输入姓名" /><span class="spa spa1"></span><br />
      <label id="phone">手机号:</label><input type="text" name="userphone" id="userphone" value="" placeholder="请输入手机号" /><span class="spa spa2"></span><br />
      <label id="address">地 址:</label><input type="text" name="useraddress" id="useraddress" value="" placeholder="请输入地址" /><span class="spa spa3"></span><br />
      <label>    </label><input type="submit" value="注册" id="sub" />
    </form>
    <script src="http://code.jquery.com/jquery-1.4.1.js"></script>
    <script type="text/javascript">
      window.onload = function() {
          $("#username").focus()
        }
        /************************ 失焦判断 **********************************/
      $("input").blur(function() {
          $(".spa").css("color", "#BD362F")
          if($(this).is("#username")) { //姓名判断
            var na = /^[\u4E00-\u9FA5]{2,4}$/
            if($("#username").val() != "") {
              if(!(na.test($("#username").val()))) {
                $(".spa1").text("请输入2-4个汉字");
                $(this).css("border", "1px solid #BD362F")
                return false;
              } else if(na) {
                $(".spa1").text("");
                return true;
              }
            } else {
              $(".spa1").text("");
            }
          }
          if($(this).is("#userphone")) { //手机号判断
            var ph = /^1[3|5|7|8|][0-9]{9}$/
            if($("#userphone").val() != "") {
              if(!(ph.test($("#userphone").val()))) {
                $(".spa2").text("请输入正确手机号");
                $(this).css("border", "1px solid #BD362F")
                return false;
              } else if(ph) {
                $(".spa2").text("");
                return true;
              }
            } else {
              $(".spa2").text("");
            }
          }

          if($(this).is("#useraddress")) { //地址判断
            var ad = /^(?=.*?[\u4E00-\u9FA5])[\dA-Za-z\u4E00-\u9FA5]{8,32}/;
            if($("#useraddress").val() != "") {
              if(!(ad.test($("#useraddress").val()))) {
                $(".spa3").text("请输入正确地址");
                $(this).css("border", "1px solid #BD362F")
                return false;
              } else if(ad) {
                $(".spa3").text("");
                return true;
              }
            } else {
              $(".spa3").text("");
            }
          }
        })
        /********************** 聚焦提示 ************************/
      $("input").focus(function() {
          if($(this).is("#username")) {
            $(".spa1").text("四个汉字").css("color", "#aaa")
            $(this).css("border", "1px solid #aaa")
          }
          if($(this).is("#userphone")) {
            $(".spa2").text("11位手机号码").css("color", "#aaa")
            $(this).css("border", "1px solid #aaa")
          }
          if($(this).is("#useraddress")) {
            $(".spa3").text("最少8个字符(汉字、字母和数字)").css("color", "#aaa")
            $(this).css("border", "1px solid #aaa")
          }
        })
        /*********************** 提交验证 ***************************/
      $("#sub").click(function() {
        var na = /^[\u4E00-\u9FA5]{2,4}$/; //姓名正则
        var ph = /^1[3|5|7|8|][0-9]{9}$/; //手机号正则
        var ad = /^(?=.*?[\u4E00-\u9FA5])[\dA-Za-z\u4E00-\u9FA5]{8,32}/; //地址正则
        if(na.test($("#username").val()) && ph.test($("#userphone").val()) && ad.test($("#useraddress").val())) {
          return true;
        } else {
          if($("#username").val() == "") {
            $(".spa1").text('请你填写用户名')
          }
          if($("#userphone").val() == "") {
            $(".spa2").text('请你填写手机号')
          }
          if($("#useraddress").val() == "") {
            $(".spa3").text('请你填写地址')
          }
          return false;
        }
      })
    </script>
  </body>
</html>

加载全部内容

相关教程
猜你喜欢
用户评论