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

Kendo UI验证错误消息显示在错误字段的问题排查

Kendo UI表单验证错误消息错位问题

问题描述

在使用Kendo UI进行表单验证时,当在Zip字段(txtZip)中输入包含无效字符的内容(如87/9*8-=+),点击验证按钮后,错误消息并未显示在Zip字段上,而是错误地显示在City字段(txtCity)中。

代码示例

JavaScript代码

$(document).ready(() => {
  CreateValidation();
  $("#btn").on("click", (e) => {
    const val = $("#NewCustomer").getKendoValidator();
    if (val) {
      val.validate();
    }
  });
});

function CheckString(str) {
  if (str.length == 0) {
    return false;
  } else {
    const re = /^[a-zA-Z0-9\s\[\]\.\\="\-#']*$/;
    return re.test(str);
  }
}

function CreateValidation() {
  const CustomerInputs = $("#NewCustomer").kendoValidator({
    errorTemplate: ({
      message
    }) => `<span style="color:red">${message}</span>`,
    messages: {
      StringCheck: "Contains invalid characters",
      required: ""
    },
    rules: {
      StringCheck: function(input) {
        if (input.is("[check-for=string]")) {
          return CheckString(input.val());
        }
        return true;
      }
    }
  }).getKendoValidator();
}

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2023.1.425/js/kendo.all.min.js"></script>

<div id="NewCustomer">
  <div class="col-md-4">
    <input id="txtCity" label-name="City" required check-for="string" type="text" class="form-control input-sm max-size" placeholder="City" />
  </div>

  <div class="col-md-4">
    <input id="txtZip" required label-name="Zip" type="text" check-for="string" class="form-control input-sm" placeholder="Zip" />
  </div>
</div>

<button id="btn">Click Me</button>

问题成因

  1. 缺失标准标签关联:Kendo UI Validator默认依赖<label for="输入框ID">这种标准标签关联方式来确定错误消息的显示位置。你的代码仅使用了自定义的label-name属性,没有为输入框添加对应的<label>元素,导致Validator无法准确将错误消息与目标输入框绑定,只能默认选择DOM中第一个匹配验证规则的元素(City字段)来显示错误。

  2. 自定义规则的遍历顺序影响:StringCheck规则会匹配所有带有check-for="string"属性的输入框,而Validator会按照DOM元素的顺序遍历验证。当Zip字段验证失败时,如果City字段也未通过StringCheck规则(比如City为空时,CheckString函数因输入长度为0返回false),错误消息会被附加到第一个未通过验证的元素上,也就是City字段。

  3. Required规则空消息的干扰:你将required规则的消息设为空字符串,当City字段为空时,Required规则的错误不会显示,但StringCheck规则会触发并返回失败,此时Validator会将StringCheck的错误消息显示在City字段,掩盖了Zip字段的验证错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:22:24