jQuery仅在提交时验证规则

前端之家收集整理的这篇文章主要介绍了jQuery仅在提交时验证规则前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有一个表格查找城市,州位置。如果用户输入不正确的城市,状态,我希望表单能够根据用户输入检查数据库,并查看输入是否有效。如果不是,我希望用户提示

所以形式验证是我的插件

  1. $("#form").validate({
  2. rules: {
  3. citystate: {
  4. required: true,myCustomAjaxSyncronousCheckAgainstDBRule: true
  5. }
  6.  
  7. submitHandler: function(form) {
  8. if ($("#form").valid()) {
  9. form.submit();
  10. }
  11. }
  12. });

现在说这个表单必须在我的网站的4个不同的地方使用,所以它会吸引重构myCustomAjaxSyncronousCheckAgainsDBRule(假名称btw),并在我的网站上有相同的代码4次。所以这就是为什么我在JS文件中创建一个自定义规则。但是有一种方法,只能在提交时检查规则。因为如果有一个无效的用户输入,它会检查它在每一个关键的中风,这可能是相当麻烦的。特别是因为我有jQuery.ui.autocomplete运行不一致。

解决方法

作为一种替代方法,您可以将函数传递给jquery.validator的onfocusout和onkeyup设置,以决定是否必须在这些事件中验证元素,如下所示:
  1. jQuery.validator.defaults.onfocusout = function (element,event) {
  2. // detectect if is the element you dont want validate
  3. // the element has to have the attribute 'data-control="mycitycontrol"'
  4. // you can also identify your element as you please
  5. if ($(element).data("control") === "mycitycontrol") return;
  6. if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
  7. this.element(element);
  8. }
  9. }
  10. jQuery.validator.defaults.onkeyup = function (element,event) {
  11. // detectect if is the element you dont want validate
  12. // the element has to have the attribute 'data-control="mycitycontrol"'
  13. // you can also identify your element as you please
  14. if ($(element).data("control") === "mycitycontrol") return;
  15. if (event.which === 9 && this.elementValue(element) === "") {
  16. return;
  17. }
  18. else if (element.name in this.submitted || element === this.lastElement) {
  19. this.element(element);
  20. }
  21. }

猜你在找的jQuery相关文章