jQuery表单验证正则表达式

时间:2015-03-11 09:19:57

标签: jquery forms validation

我正在做一切正确的验证用户名和密码,但仍无效。

<script>

$(document).ready(function(){
    $('#username1').keyup(function() {
        $('span.error').hide();
        var inputVal = $(this).val();
        var usernameReg = /^[a-zA-Z0-9._-]{3,16}$/;
        if(!usernameReg.test(inputVal)) {
            $(this).after('<span class="error">Username 3-16 characters long containing letters, numbers and underscore only.</span>');
        }
    });

    $('#password1').keyup(function() {
        $('span.error').hide();
        var inputVal = $(this).val();
        var passwordReg = /^[A-Za-z0-9!@#$%^&*()_]{6,16}$/;
        if(!passwordReg.test(inputVal)) {
            $(this).after('<span class="error">Password must be atleast 6 characters long.</span>');
        }
    });
});

</script> 

1 个答案:

答案 0 :(得分:0)

一个问题是隐藏错误,所以

$(document).ready(function() {
  $('#username1').keyup(function() {
    var inputVal = $(this).val();
    var usernameReg = /^[a-zA-Z0-9._-]{3,16}$/;
    var $error = $(this).next('span.error');
    if (!usernameReg.test(inputVal)) {
      if ($error.length) {
        $error.show()
      } else {
        $(this).after('<span class="error">Username 3-16 characters long containing letters, numbers and underscore only.</span>');
      }
    } else {
      $error.hide();
    }
  });
  $('#password1').keyup(function() {
    var inputVal = $(this).val();
    var passwordReg = /^[A-Za-z0-9!@#$%^&*()_]{6,16}$/;
    var $error = $(this).next('span.error');
    if (!passwordReg.test(inputVal)) {
      if ($error.length) {
        $error.show()
      } else {
        $(this).after('<span class="error">Password must be atleast 6 characters long.</span>');
      }
    } else {
      $error.hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <input id="username1" />
</div>
<div>
  <input id="password1" />
</div>