我在我的项目中使用jQuery v1.7.1。
我有以下 HTML 表单:
<div class="alert-danger">
</div>
<form action="index.php" class="navbar-form pull-right" id="formzip" method="post">
<input type="hidden" class="form-control" name="op" id="op" value="zip_code">
<input type="hidden" class="form-control" name="form_submitted" id="form_submitted" value="yes">
<input style="width: 115px;" type="text" placeholder="Enter the zip code" name="zip" id="zip" value=""> <i class="icon-zip" style="margin-top:3px;" onclick='$("#formzip").submit();'></i>
</form>
现在我想用 id="formzip"
验证表单使用 jQuery。需要应用以下验证:
- 如果提交表单时 ID 为 zip 的输入字段不包含任何值。
- 如果 ID 为 zip 的输入字段包含无效的美国邮政编码值或任何不是有效美国邮政编码的值。
我想在 <div class="alert-danger"></div>
中显示相关错误消息并想要阻止表单提交。也就是说,当前显示的页面应保持原样。
验证美国邮政编码所需的正则表达式字符串如下:
"/^([0-9]{5})(-[0-9]{4})?$/i"
有人可以帮我实现这个功能吗?
如果有人能帮助我,这将对我有很大帮助。
感谢您花费宝贵的时间来理解我的问题。如果您想了解有关我的问题的更多信息,请随时询问我。
等待您的宝贵回复。
提前致谢。
最佳答案
你可以这样做:-
$(function(){
$('#formzip').on('submit',function(){
if($('#zip').val()=='')
{
$('.alert-danger').html('zipcode is empty');
return false;
}else if(!isValidZip($('#zip').val()))
{
$('.alert-danger').html('zipcode is invalid');
return false;
}
});
});
function isValidZip(zip) {
var pattern = new RegExp(/^([0-9]{5})(-[0-9]{4})?$/i);
return pattern.test(zip);
};
或者如果您想显示相同的消息,您可以这样做:-
$('#formzip').on('submit',function(){
if(!isValidZip($('#zip').val()))
{
$('.alert-danger').html('zipcode is invalid');
return false;
}
});
关于javascript - 如何使用 jQuery 验证表单、阻止提交表单并在指定的 div 中显示正确的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26211995/