jQuery中的表单验证

html代码

<section id="register">
    <div><img src="images/logo.jpg" alt="logo" /><img src="images/banner.jpg" alt="banner" /></div>
    <h1 class="hr_1">新用户注册</h1>
    <form action="" method="post" name="myform">
        <dl>
            <dt>用户名:</dt>
            <dd><input id="user" type="text" /><div id="user_prompt">用户名由英文字母和数字组成的4-16位字符,以字母开头</div></dd>
        </dl>
        <dl>
            <dt>密码:</dt>
            <dd><input id="pwd" type="password"  /><div id="pwd_prompt">密码由英文字母和数字组成的4-10位字符</div></dd>
        </dl>
        <dl>
            <dt>确认密码:</dt>
            <dd><input id="repwd" type="password"/><div id="repwd_prompt"></div></dd>
        </dl>
        <dl>
            <dt>电子邮箱:</dt>
            <dd><input id="email" type="text"/><div id="email_prompt"></div></dd>
        </dl>
        <dl>
            <dt>手机号码:</dt>
            <dd><input id="mobile" type="text" /><div id="mobile_prompt"></div></dd>
        </dl>
        <dl>
            <dt>生日:</dt>
            <dd><input id="birth" type="text"/><div id="birth_prompt"></div></dd>
        </dl>
        <dl>
            <dt>&nbsp;</dt>
            <dd><input name="" type="image" src="images/register.jpg" class="btn" /></dd>
        </dl>
  </form>
</section>

jQuery代码

<script>
    $(function(){
        $("#user").blur(checkname)
        $("#pwd").blur(checkpwd)
        $("#mobile").blur(checkmobile)
        $("#birth").blur(checkbirth)
    })
    function checkname(){
     var names=/^[a-zA-Z][a-zA-Z0-9]{3,15}$/
        var $users=$("#user_prompt")
        var $user=$("#user").val()
        if(names.test($user)==false){
            $users.html("用户名由英文字母和数字组成的4-16位字符,以字母开头")
            return false;
        }
        $users.html("");
        return true;
    }
    function checkpwd(){
        var pwds=/^[a-zA-Z0-9]{4,10}$/
        var pwd=$("#pwd").val();
        var $pwds=$("#pwd_prompt")
        if(pwds.test(pwd)==false){
            $pwds.html("密码由英文字母和数字组成的4-10位字符")
            return false
        }
        $pwds.html("")
        return true;
    }
    function checkmobile(){
        var mobile=/^1[0-9]{10}$/
        var mobiles=$("#mobile").val()
        var $mobile=$("#mobile_prompt")
        if(mobile.test(mobiles)==false){
            $mobile.html("手机号码只能是1开头的11位数字")
            return false
        }
        $mobile.html("")
        return true
    }
  function checkbirth(){
         var birth=/^((19\d{2})|(200\d)|(201[0-6]))-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2]\d|3[0-1])$/   //出生日期不在2016年之后
  var births=$("#birth").val();
      var $birth=$("#birth_prompt")
      if(birth.test(births)==false){
          $birth.html("生日格式不正确")
      return false
      }
      $birth.html("")
      return true
  }

</script>

猜你喜欢

转载自www.cnblogs.com/yjc1605961523/p/11075232.html