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

如何在Kendo Grid中批量显示多字段验证错误

Kendo UI Grid 批量验证所有错误单元格实现方法

核心思路

拦截保存按钮的默认提交行为,手动遍历网格所有行和可编辑列,逐一触发验证规则,批量标记所有不符合规则的单元格并显示错误信息,最后根据验证结果决定是否提交后端。

具体实现步骤


1. 拦截保存按钮点击事件

给保存按钮绑定点击事件,阻止默认提交,先执行前端批量验证:

$("#saveBtn").on("click", function(e) {
    e.preventDefault();
    const grid = $("#grid").data("kendoGrid");
    let hasErrors = false;

    // 清除之前的错误标记和提示
    grid.table.find(".k-invalid").removeClass("k-invalid");
    grid.table.find(".k-error-message").remove();

    // 遍历网格所有行
    grid.tbody.find("tr").each(function() {
        const dataItem = grid.dataItem(this);
        const row = $(this);

        // 遍历所有可编辑列
        grid.columns.forEach(column => {
            if (!column.editable || !column.field) return; // 跳过非编辑列/无字段列

            const field = column.field;
            const value = dataItem[field];
            const validationRules = column.validation || {};
            let errorMessage = "";

            // 复用Kendo内置验证器,避免手动写规则判断
            const validator = kendo.validator({
                rules: validationRules,
                messages: validationRules.messages || {}
            });
            const tempInput = $("<input>").val(value || "");
            
            // 执行验证
            if (!validator.validateInput(tempInput)) {
                errorMessage = validator.errors()[0];
                hasErrors = true;
            }

            // 标记错误单元格并显示提示
            if (errorMessage) {
                const cell = row.find(`td[data-field="${field}"]`);
                cell.addClass("k-invalid");
                cell.append(`<span class="k-error-message">${errorMessage}</span>`);
            }
        });
    });

    // 验证通过则提交数据到后端
    if (!hasErrors) {
        // 方式1:使用Grid内置的保存方法
        grid.saveChanges();
        // 方式2:自定义AJAX提交(适合批量提交所有数据)
        // $.post("/YourController/BatchSave", { data: grid.dataSource.data() }, res => {
        //     // 处理后端响应
        // });
    }
});

2. 统一错误样式(可选)

如果默认样式不够醒目,可自定义CSS对齐Kendo风格:

.k-error-message {
    color: #dc3545;
    font-size: 0.875em;
    margin-top: 4px;
    display: block;
}
.k-invalid {
    border-color: #dc3545 !important;
    background-color: rgba(220, 53, 69, 0.05);
}

3. 适配不同编辑模式

  • Inline编辑:上述代码直接可用,单元格标记逻辑无需调整。
  • Popup编辑:需修改遍历逻辑,改为获取所有弹出的编辑窗口,逐个验证表单字段。
  • Batch编辑:可结合Grid的dataSource.total()和dataSource.view()遍历所有修改/新增的数据项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 03:19:58