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

FormValidation.io声明式模式下如何为identical校验器设置compare比较函数?

解决FormValidation声明式模式下identical校验器比对密码不生效问题

你遇到的问题是因为FormValidation的声明式插件默认会将HTML属性的取值解析为普通字符串,你在属性中写getPassword()会被直接作为字符串传给compare参数,而不会作为函数执行获取返回值,所以只有输入getPassword()字符串才能通过校验。


方案1:直接绑定目标字段name(最优方案,无需额外JS)

identical校验器的compare参数本身支持直接传入需要比对的目标表单字段的name属性值,框架会自动实时获取该字段的输入值进行比对,完全不需要额外写自定义函数。
修改后的完整代码如下:

<input
  class="form-control"
  data-fv-not-empty="true"
  data-fv-not-empty___message="The password is required" 
  type="password"
  placeholder="Password"
  name="password"
  id="input-password"
  autocomplete="off"
>
     
<input 
  class="form-control" 
  data-fv-identical="true" 
  data-fv-identical___compare="password" 
  data-fv-identical___message="The password and its confirm are not the same" 
  type="password" 
  placeholder="Confirm Password" 
  name="confirm" 
  id="input-confirm" 
  autocomplete="off"
>

注意:该方案中data-fv-identical___compare的取值必须和密码字段的name属性完全匹配,如果你修改了密码字段的name值,这里也要同步修改。


方案2:需要使用自定义函数的场景

如果你的比对逻辑有额外处理需求,必须用自定义函数实现,就需要给属性值加js:前缀标记这是JS表达式,同时只传函数名不要加括号,这样框架会识别为函数引用,校验时自动调用获取返回值:
修改后的完整代码如下:

<input
  class="form-control"
  data-fv-not-empty="true"
  data-fv-not-empty___message="The password is required" 
  type="password"
  placeholder="Password"
  name="password"
  id="input-password"
  autocomplete="off"
>
     
<input 
  class="form-control" 
  data-fv-identical="true" 
  data-fv-identical___compare="js:getPassword" 
  data-fv-identical___message="The password and its confirm are not the same" 
  type="password" 
  placeholder="Confirm Password" 
  name="confirm" 
  id="input-confirm" 
  autocomplete="off"
>
     
<script>
function getPassword() {
  return $('#input-password').val();
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:15:02