表单验证有效,但不能阻止表单提交
我使用JavaScript来验证我的表单输入,并且效果很好,但是当未纠正错误时,表格仍会提交。
在用户进行更正之前,如何防止表单提交?
下面的示例代码;
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456") {
$(".validate").show();
} else {
$(".validate").hide();
}
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>
I use javascript to validate my form input and it works fine but the form still gets submitted when errors are not corrected.
How do I prevent form submission until the user makes corrections?
Sample Code Below;
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456") {
$(".validate").show();
} else {
$(".validate").hide();
}
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<div class="validate"><span style="color: red;"><b>Phone in use!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要编写一个有用的答案,我做了一个小型重构,重写是可重复使用的验证功能,只需返回
true
或false
。我也重命名。现在,我们可以在不同位置重复使用验证逻辑。表单
元素在实际提交之前发射<代码>提交事件。我们必须收听Sumbit
事件,如果验证失败,我们可以返回将取消事件的false
,从而防止表单提交。To write a helpful answer, I made a small refactor, rewriting
isphone
to be a reusable validation function that just returnstrue
orfalse
. I renamed it too. Now we can reuse the validation logic in different places.form
elements emit asubmit
event just before they are actually submitted. We must listen for thesumbit
event, and if validation fails, we canreturn false
which will cancel the event, and therefore preventing form submission.