js面向对象加构造函数模式表单验证

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单验证</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
  <div>
    <input type="text" id="userName" value="6">
    <input type="password" id="password">
    <button id="button">提交</button>
  </div>
  <script>
    var m={
      userName:$("#userName").val(),
      password:$("#password").val(),
      userTest:/^[a-zA-Z]{1}[A-Z|a-z|0-9]{5,29}/,
      passwordTest:/^(\w){6,20}$/,//6-20个字母
      test:function(testDate, testReg,testName){
        this.testDate = testDate;
        this.testReg = testReg;
        this.testName = testName;
        this.testFormData=function(){
          if(this.testDate==''){
            alert(this.testName+'不能为空,请输入')
            return false;
          }else if(!this.testReg.test(this.testDate)){
            alert(testName+'格式不正确,请重新输入')
            return false;
          }else{
            return true;
          }
        }
      },
        page:function(){
                      alert('登录成功,欢迎来到百度')
         window.location='https://www.baidu.com'
      },
          commit:function(){
        this.userName=$("#userName").val();
        this.password=$("#password").val();
        var test=this.test;
        var userNameTest=new test(this.userName,this.userTest,'用户名');
        var passwordTest=new test(this.password,this.passwordTest,'密码');
        var userNameV=userNameTest.testFormData()
        console.log(userNameV)
        if(!userNameV){//如果用户名不规范 就直接退出运行 不进行密码验证
          return;
        }else{
          var passwordV=passwordTest.testFormData()
        }
        if(userNameV&&passwordV){
          this.page();
        }
     }
}

$('#button').click(function(){
  m.commit()
})
</script>
</body>
</html>

posted @ 2019-08-06 22:25  zouTuring  阅读(358)  评论(0编辑  收藏  举报