【发布时间】:2017-02-25 18:49:43
【问题描述】:
我使用 Jquery 构建了一个表单验证器,它会在用户键入密码表单时提示用户输入密码要求以及他们是否满足要求。此代码按我的意愿工作,如下所示:
表单验证
$('input[type=password]').keyup(function () {
// set password variable
var pwd = $(this).val();
//validate the length
if (pwd.length < 8) {
$('#length').removeClass('glyphicon glyphicon-check valid').addClass('glyphicon glyphicon-check invalid');
} else {
$('#length').removeClass('glyphicon glyphicon-check invalid').addClass('glyphicon glyphicon-check valid');
}
//validate capital letter
if (pwd.match(/[A-Z]/)) {
$('#capital').removeClass('glyphicon glyphicon-check invalid').addClass('glyphicon glyphicon-check valid');
} else {
$('#capital').removeClass('glyphicon glyphicon-check valid').addClass('glyphicon glyphicon-check invalid');
}
//validate number
if (pwd.match(/[0-9]/)) {
$('#number').removeClass('glyphicon glyphicon-check invalid').addClass('glyphicon glyphicon-check valid');
} else {
$('#number').removeClass('glyphicon glyphicon-check valid').addClass('glyphicon glyphicon-check invalid');
}
}).focus(function () {
$('#pwd_info').show();
}).blur(function () {
$('#pwd_info').hide();
});
});
现在,我想阻止在满足这些要求之前提交按钮,并且我已将以下功能添加到我的文档中尝试这样做:
停止表单提交
$(document).ready(function () {
$('#signup_btn').submit(function (e) {
var pwd = $('input[type=password]').val();
if (pwd.length < 8) {
e.preventDefault();
}
if (pwd.match(/[A-Z]/)) {
e.preventDefault();
}
if (pwd.match(/[0-9]/)) {
e.preventDefault();
}
else
return true;
});
当我尝试根据我的条件(1 个数字、1 个大写字母和最少 8 个字符)提交无效密码时,它仍然允许我通过。有人可以指出我正确的方向吗?
【问题讨论】:
-
你的
else语句只对应最后一个if。
标签: jquery forms preventdefault