我要验证登录表单。当我仅验证手机号码时,它工作正常。如果我同时验证了手机和密码,那么只有最后一个有效,其余的则无法正常工作。谁能帮我,这段代码有什么问题?
我尝试过的事情:
function loginValidation() {
if ($('[name="mobileNo"]').val() == '') {
$('.validation_error').text('Mobile number is reuired').addClass('validation_active');
} else {
$('.validation_error').text('').removeClass('validation_active');
}
if ($('[name="loginPassword"]').val() == '') {
$('.validation_error').text('Password is reuired').addClass('validation_active');
} else {
$('.validation_error').text('').removeClass('validation_active');
}
setTimeout(function() {
$('.validation_error').text('').removeClass('validation_active');
}, 3000);
};
.validation_error {
position: fixed;
bottom: 20px;
width: 80%;
height: auto;
text-align: center;
left: 0px;
right: 0px;
margin-left: auto;
margin-right: auto;
background: #ee2e24;
z-index: 10000;
color: #fff;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
box-shadow: 2px 4px 39px #333;
transition: all 0.45s;
transform: translateY(100px);
}
.validation_active {
transform: translateY(0px);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div id="loginBox">
<div class="form-group">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text"><i class="fa fa-phone"></i></span>
</div>
<input type="text" class="form-control" placeholder="Mobile No" name="mobileNo">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" class="form-control" placeholder="Password" name="loginPassword">
</div>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-lg" onclick="loginVelidation();">Login</button>
</div>
</div>
<div class="validation_error"></div>
当我单击登录按钮时,现在显示password is reuired
。但是首先我要验证mobile is reuired
答案 0 :(得分:0)
您的代码正确,但是如果您想同时显示两个错误,那么您将覆盖错误消息$('。validation_error'),然后您将创建一个单独的错误持有者元素。
答案 1 :(得分:0)
您可以尝试以下方法吗:
function loginVelidation()
{
if ($('[name="mobileNo"]').val() == '') {
$('.validation_error').text('Mobile number is reuired').addClass('validation_active');
}
else if ($('[name="loginPassword"]').val() == '') {
$('.validation_error').text('Password is reuired').addClass('validation_active');
else {
$('.validation_error').text('').removeClass('validation_active');
}
setTimeout(function() {
$('.validation_error').text('').removeClass('validation_active');
}, 3000);
};