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

jQuery Validate校验表单重复值时二次点击保存旧非法项变合法问题

问题根因

该异常表现由三个核心问题导致:

  1. jQuery Validate初始化时只会捕获当前表单已存在的字段,后续动态新增的声明项关联的隐藏输入框,没有被校验器纳入校验列表,默认不会触发校验
  2. jQuery Validate默认只对「值发生过变更的脏字段」执行校验,新增重复值后,原来的旧重复字段值没有变化,默认不会重新执行校验规则,导致原来的错误提示消失,只有新增的字段被校验
  3. 初始渲染的静态声明项对应的隐藏输入框,没有添加duplicateClaimName类,不会触发重复值校验规则

修复方案

1. 修复静态字段的类缺失

修改Razor代码中的静态隐藏输入框,添加校验类:

<input id="hidden-claim-value" name="CustomClaims[@i].ClaimLabel" type="hidden" class="duplicateClaimName" value="@Model.CustomClaims[i].ClaimLabel" />

2. 动态新增字段后主动注册校验规则

在oidc_addCustomProfileClaim函数末尾,新增字段插入表单后,主动给新增的隐藏输入框注册校验规则:

// 原有代码 div.append(newDiv); 之后新增以下逻辑
$('input[name="CustomClaims[' + lastId + '].ClaimLabel"]').rules('add', {
    checkForDuplicateClaimName: true,
    messages: {
        checkForDuplicateClaimName: "Duplicate Name"
    }
});

3. 提交前强制全量重校验所有重复字段

修改表单提交事件逻辑,提交前强制所有带duplicateClaimName类的字段重新执行校验,避免旧字段因为值无变更跳过校验:

$('form.form-horizontal').submit(function (e) {
    console.log('calling submit form');
    // 强制所有重复值校验字段重新执行校验
    $('.duplicateClaimName').each(function() {
        $(this).valid();
    });
    // 全表单校验不通过则阻止提交
    if (!validate.form()) {
        e.preventDefault();
        return false;
    }
    console.log(validate);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:00:00