我有一个非常具体的问题。我在页面上有两个表单,包括bootstrap验证器,它工作正常,但它没有对电子邮件输入进行RegEx检查。所以我创建了一个简短的RegEx验证,但是当我尝试处理错误消息时,它们只能用于第二种形式。单击“提交”按钮时,两个表单上都会显示错误消息,但超时功能仅适用于后者。顶部表单的“提交”按钮会在我点击它时不断创建新的错误消息。有什么建议?请参阅下面的代码:
HTML:
最高形式:
<form action="" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name:" required>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email Address:" required>
</div>
<div class="form-group">
<input type="tel" class="form-control" name="phone" placeholder="Phone Number:" required>
</div>
<div class="form-group">
<input type="text" class="form-control" name="amount" placeholder="Investment Amount (£)">
</div>
<button class="btn btn-block btn-submit" type="submit" name="submit">Enquire Now</button>
底部形式:
<form action="" method="POST" class="row form-find-more">
<div class="form-group col-lg-3 col-md-3">
<input type="text" name="name" placeholder="Full Name*:" required>
</div>
<div class="form-group col-lg-3 col-md-3">
<input type="email" name="email" placeholder="Email Address*:" required>
</div>
<div class="form-group col-lg-3 col-md-3">
<input type="text" name="phone" placeholder="Phone Number*:">
</div>
<div class="form-group col-lg-3 col-md-3">
<button class="btn" type="submit" name="submit">Submit Request</button>
</div>
</form>
我的jQuery代码段:
<script>
var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|
(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var elm = $('<div class="help-block with-errors">Please enter a valid e-
mail</div>');
$(document).on('click', 'form button[type=submit]', function(e) {
var isValid = emailReg.test(jQuery.trim($(e.target).parents('form').find("input[type=email]").val()));
if(!isValid) {
e.preventDefault(); //prevent the default action
$('form').append(elm);
}
});
setTimeout(function() {
elm.detach();
}, 5000);
</script>
答案 0 :(得分:0)
通过一些代码编辑来管理解决问题:
var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|
(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-
9]+\.)+[a-zA-Z]{2,}))$/;
var elm = $('<div class="help-block with-errors">Please enter a valid e-mail</div>');
$(document).on('click', 'form button[type=submit]', function(e) {
var isValid = emailReg.test(jQuery.trim($(e.target).parents('form').find("input[type=email]").val()));
if(!isValid) {
e.preventDefault(); //prevent the default action
$('form').append(elm.prop('outerHTML'));
setTimeout(function() {
$('.help-block.with-errors').remove();
}, 3000);
}
});
感谢所有帮助过的人。