jqGrid-字段验证 [英] jqGrid - Validation of fields

查看:297
本文介绍了jqGrid-字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jqGrid进行内联编辑,以及在使用添加"按钮创建新记录时使用.

I am using jqGrid for inline editing and also when creating new record with the Add button.

为简单起见,假设我有2个字段

For sake of simplicity, say I have 2 fields

Field1   Field2

我需要以下规则

  • 如果用户未在Field1或Field2中输入任何内容,则无需验证
  • 如果用户确实输入了数据,则可以在Field1或Field2中输入数据,但不能同时输入两者

推荐答案

jqGrid的验证可能性有很多限制,尤其是在内联编辑期间的验证.实现验证的方法$.jgrid.checkValues将被调用(请参见

The validation possibilities of jqGrid has many restrictions especially validation during inline editing. The method $.jgrid.checkValues, which implements the validation will be called (see the line of source code), will be called directly during reading of the corresponding input field. So one have no information about other fields as the current validating.

作为解决方法,您可以在字段验证期间保存Field1中的值. Filed2的验证可以同时验证两个字段. 自定义验证是您可以使用的方式在这种情况下.

As the workaround you can save the value from the Field1 during the field validation. The validation of the Filed2 can do the validation of the both fields. The custom validation is the way which you can use in the case.

var field1, field2,
    myCustomCheck = function (value, colname) {
        if (colname === "field1") {
            field1 = value;
        } else if (colname === "field2") {
            field2 = value;
        }

        if (field1 !== undefined && field2 !== undefined) {
            // validate the fields here
            return [false, "some error text"];
        } else {
            return [true];
        }
    };

$("#grid").jqGrid({
    ...
    colModel: [ 
        ... 
        {name: 'field1', editable: true, ...,
            editrules: {custom: true, custom_func: myCustomCheck}},
        ...
        {name: 'field2', editable: true, ...,
            editrules: {custom: true, custom_func: myCustomCheck}},
        ...
    ]
    ...
});

您不应该忘记在编辑之前或之后(在oneditfuncaftersavefunc或其他回调中)将field1field2变量重置为undefined值.

You should don't forget to reset field1 and field2 variables to undefined value either before or after editing (in oneditfunc, aftersavefunc or some other callback).

我在上面的代码中使用了field1field2验证的对称"版本,以使代码在字段顺序更改的情况下也可以工作,如果您使用

I used in the above code the "symmetric" version of field1 and field2 validation to make the code working in case of changed order of the fields, which can be important if you use columnChooser. In the case you can't be sure that field1 will be always validated before the field2.

您可以使用现有jqGrid方法的子类化"来存档一些其他效果.参见答案作为示例.

Some additional effects you can archive by usage of "subclassing" of existing jqGrid methods. See the answer as an example.

已更新:演示更加详细地演示上述验证想法.

UPDATED: The demo demonstrate the above idea of the validation more detailed.

这篇关于jqGrid-字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆