You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用on('validation')时validate函数多次触发的表单验证问题

解决表单字段失焦时validation事件触发次数递增的问题

看起来你遇到的核心问题是事件处理函数被重复绑定,导致每次失焦时触发次数不断累加。下面是具体的分析和解决方案:

问题根源

你当前的事件绑定方式是直接绑定到表单元素上,如果你的初始化代码(包括事件绑定部分)被多次执行(比如页面组件重新渲染、$.validate()被重复调用等),就会给同一个元素重复添加validation和beforeValidation事件处理函数,触发时自然会执行多次,且次数递增。

另外,jQuery Validation插件内部的验证流程若和自定义绑定叠加,也可能加剧这个问题,但核心矛盾还是重复绑定。

解决方案

方案1:绑定前先解绑旧事件

在绑定新的事件处理函数之前,先移除元素上已有的同名事件,确保每次绑定都是唯一的:

// 先解绑旧的事件处理函数,再绑定新的
$('input:not([type=radio]),textarea')
  .off('validation beforeValidation')
  .on('validation', function(evt, valid) {
    var error_div = $(this).parents(".parent-input").find('.custom-error');
    if (!valid) {
      var error_message = evt.target.dataset.validationErrorMsg || "Please provide a valid input";
      error_div.html(error_message);
    } else {
      error_div.html("");
      saveField();
      console.log("I CALL THE SAVE FUNCTION!");
    }
  })
  .on('beforeValidation', function(value, lang, config) {
    var error_div = $(this).parents(".parent-input").find('.custom-error');
    error_div.html("");
  });

方案2:使用事件委托(更推荐)

将事件绑定到表单父元素上,利用事件冒泡机制处理子元素的事件,这样只会绑定一次,彻底避免重复绑定的问题:

// 绑定到表单元素上,通过选择器过滤目标子元素
$('#form-1')
  .on('validation', 'input:not([type=radio]),textarea', function(evt, valid) {
    var error_div = $(this).parents(".parent-input").find('.custom-error');
    if (!valid) {
      var error_message = evt.target.dataset.validationErrorMsg || "Please provide a valid input";
      error_div.html(error_message);
    } else {
      error_div.html("");
      saveField();
      console.log("I CALL THE SAVE FUNCTION!");
    }
  })
  .on('beforeValidation', 'input:not([type=radio]),textarea', function(value, lang, config) {
    var error_div = $(this).parents(".parent-input").find('.custom-error');
    error_div.html("");
  });

额外检查:确保$.validate()只初始化一次

检查代码中是否存在多次调用$.validate()的情况,重复初始化插件会导致内部事件重复绑定,进一步加剧问题。建议将初始化代码放在$(document).ready()中,确保只执行一次:

$(document).ready(function() {
  $.validate({ 
    form: '#form-1', 
    modules: 'location, logic, html5, security', 
    onModulesLoaded: function() { 
      $('input.hasCountry').suggestCountry(); 
    } 
  });

  // 这里放事件绑定代码(方案1或方案2)
});

验证方法

修改代码后,多次聚焦/失焦字段,查看控制台的console.log输出,应该每次失焦只触发一次,不再出现递增的情况。

内容的提问来源于stack exchange,提问作者Amjo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:35:41