javascript - 如何使用 jQuery 验证表单、阻止提交表单并在指定的 div 中显示正确的错误消息?

标签 javascript jquery forms validation jquery-1.7

我在我的项目中使用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。需要应用以下验证:

  1. 如果提交表单时 ID 为 zip 的输入字段不包含任何值。
  2. 如果 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;
  }
});

Demo

关于javascript - 如何使用 jQuery 验证表单、阻止提交表单并在指定的 div 中显示正确的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26211995/

相关文章:

javascript - window.print() 在 Firefox 中不工作

javascript - 我可以在 Android 浏览器中仅使用 javascript 启动 Intent 吗?

javascript - $.getJSON 没有将数据保存到全局变量/对象中,该变量/对象是本地的

Jquery 从文本 "2-6"创建数组,如 [2,3,4,5,6]

javascript - jQuery 或 Javascript 在提交时解析查询字符串

javascript - 更新 Observablehq react 环境中的单元格值

javascript - 使用 call 或 apply 调用 jQuery 函数

php - 两次单击以填充表单

html - 多个表单标签是不是一个坏主意?

javascript - mongodb - 汇总和展开外国引用文件