如何将电话号码和电子邮件验证添加到Kendo-UI Grid

How do I add phone number & email validation to Kendo-UI Grid?

本文关键字:添加 Kendo-UI Grid 验证 电子邮件 电话号码      更新时间:2023-09-26

给定以下代码中提供的网格,如何在电话电子邮件上设置验证以利用 kendo 在此页面上提供的验证和屏蔽输入功能(http://demos.telerik.com/kendo-ui/maskedtextbox/index)?

例如,如果用户键入5628103322,则应将其格式设置为(562)810-3322,如其页面上的演示所示。 此外,如果数字输入不正确,则应提供错误消息。

电子邮件也是如此,我们如何做到这一点?

<div id="grid"></div>
<script>
    var crudServiceBaseUrl = "/api",
    dataSource = new kendo.data.DataSource({
        transport: {
            read:  {
                url: crudServiceBaseUrl + "/companies",
                dataType: "json",
                type: "POST"
            },
            update: {
                url: crudServiceBaseUrl + "/companies/update",
                dataType: "json",
                type: "POST"
            },
            destroy: {
                url: crudServiceBaseUrl + "/companies/destroy",
                dataType: "json",
                type: "POST"
            },
            create: {
                url: crudServiceBaseUrl + "/companies/create",
                dataType: "json",
                type: "POST"
            },
            parameterMap: function(options, operation) {
                if (operation !== "read" && options.models) {
                    return {models: kendo.stringify(options.models)};
                }
            }
        },
        error: function (e) {
            /* the e event argument will represent the following object:
            {
                errorThrown: "Unauthorized",
                sender: {... the Kendo UI DataSource instance ...}
                status: "error"
                xhr: {... the Ajax request object ...}
            }
            */
            //alert("Status: " + e.status + "; Error message: " + e.errorThrown);
            console.log("Status: " + e.status + "; Error message: " + e.errorThrown);
        },
        autoSync: false,
        serverPaging: true,
        serverFiltering: true,
        serverSorting: true,
        pageSize: 20,
        selectable: "multiple cell",
        allowCopy: true,
        columnResizeHandleWidth: 6,
        schema: {
            total: "itemCount",
            data: "items",
            model: {
                id: "id",
                fields: {
                    id: { editable: false, nullable: true },
                    name: { validation: { required: true } },
                    phone: { type: "string" },
                    email: { type: "string" }
                }
            }
        }
    });
    $("#grid").kendoGrid({
        dataSource: dataSource,
        height: 550,
        groupable: true,
        sortable: {
            mode: "multiple",
            allowUnsort: true
        },
        toolbar: ["create"],
        pageable: {
            refresh: true,
            pageSizes: true,
            buttonCount: 5
        },
        reorderable: true,
        resizable: true,
        columnMenu: true,
        filterable: true,
        columns: [
            { field: "name", title: "Company Name" },
            { field: "phone", title:"Phone" },
            { field: "email", title:"Email" },
            { command: ["edit", "destroy"], title: "Operations", width: "240px" }
        ],
        editable: "popup"
    });
</script>

更新::

$("#grid").kendoGrid({
        dataSource: dataSource,
        groupable: true,
        sortable: {
            mode: "multiple",
            allowUnsort: true
        },
        toolbar: ["create"],
        pageable: {
            refresh: true,
            pageSizes: true,
            buttonCount: 5
        },
        reorderable: true,
        resizable: true,
        columnMenu: true,
        filterable: true,
        columns: [
            { field: "name", title: "Company Name" },
            { 
                field: "phone",
                title: "Phone",
                editor: function(container, options){
                    var input = $('<input type="tel" data-tel-msg="Invalid Phone Number!" class="k-textbox"/>');
                    input.attr("name", options.field);
                    input.kendoMaskedTextBox({
                        mask: "(999) 000-0000"
                    });
                    input.appendTo(container);
                }
            },
            { 
                field: "email",
                title: "Email",
                editor: function(container, options){
                    var input = $('<input type="email" data-email-msg="Invalid email!" class="k-textbox"/>');
                    input.attr("name", options.field);
                    input.appendTo(container);
                }
            },
            { command: ["edit", "destroy"], title: "Operations", width: "240px" }
        ],
        editable: "popup"
    });

上面的网格代码已更改,由于下面的答案,它现在几乎可以完美运行,现在我只需要弄清楚如何向电话号码和电子邮件字段添加验证,因此需要输入并正确输入。

更新 #2

由于答案,下面的代码现在可以完美运行,只是想将其分享给可能需要帮助的其他人。 需要注意的有趣一点是,无论破折号中间的文本data-phonerule-msg,都必须命名模型规则 phonerule。 我猜剑道-UI在寻找自定义规则时必须寻找它。

<div id="grid" style="height:100%;"></div>
<script>
    $(window).on("resize", function() {
      kendo.resize($("#grid"));
    });
    var crudServiceBaseUrl = "/api",
    dataSource = new kendo.data.DataSource({
        transport: {
            read:  {
                url: crudServiceBaseUrl + "/companies",
                dataType: "json",
                type: "POST"
            },
            update: {
                url: crudServiceBaseUrl + "/companies/update",
                dataType: "json",
                type: "POST"
            },
            destroy: {
                url: crudServiceBaseUrl + "/companies/destroy",
                dataType: "json",
                type: "POST"
            },
            create: {
                url: crudServiceBaseUrl + "/companies/create",
                dataType: "json",
                type: "POST"
            },
            parameterMap: function(options, operation) {
                if (operation !== "read" && options.models) {
                    return {models: kendo.stringify(options.models)};
                }
            }
        },
        error: function (e) {
            /* the e event argument will represent the following object:
            {
                errorThrown: "Unauthorized",
                sender: {... the Kendo UI DataSource instance ...}
                status: "error"
                xhr: {... the Ajax request object ...}
            }
            */
            //alert("Status: " + e.status + "; Error message: " + e.errorThrown);
            console.log("Status: " + e.status + "; Error message: " + e.errorThrown);
        },
        autoSync: false,
        serverPaging: true,
        serverFiltering: true,
        serverSorting: true,
        pageSize: 20,
        selectable: "multiple cell",
        allowCopy: true,
        columnResizeHandleWidth: 6,
        schema: {
            total: "itemCount",
            data: "items",
            model: {
                id: "id",
                fields: {
                    id: { editable: false, nullable: true },
                    name: { validation: { required: true } },
                    phone: { 
                        type: "string",
                        validation: { 
                            required: true,
                            phonerule: function(e){
                                if (e.is("[data-phonerule-msg]"))
                                {
                                    var input  = e.data('kendoMaskedTextBox');
                                    //If we reached the end of input then it will return -1 which means true, validation passed
                                    //Otherwise it won't === -1 and return false meaning all the characters were not entered.
                                    return input.value().indexOf(input.options.promptChar) === -1;
                                }
                                return true; //return true for anything else that is not data-phonerule-msg
                            } 
                        } 
                    },
                    email: { type: "string", validation: { required: true, email:true } }
                }
            }
        }
    });
    $("#grid").kendoGrid({
        dataSource: dataSource,
        groupable: true,
        sortable: {
            mode: "multiple",
            allowUnsort: true
        },
        toolbar: ["create"],
        pageable: {
            refresh: true,
            pageSizes: true,
            buttonCount: 5
        },
        reorderable: true,
        resizable: true,
        columnMenu: true,
        filterable: true,
        columns: [
            { field: "name", title: "Company Name" },
            { 
                field: "phone",
                title: "Phone",
                editor: function(container, options){
                    //pattern="[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}"
                    var input = $('<input type="tel" data-phonerule-msg="Invalid Phone Number!" class="k-textbox"  required />');
                    input.attr("name", options.field);
                    input.kendoMaskedTextBox({
                        mask: "(999) 000-0000"
                    });
                    input.appendTo(container);
                }
            },
            { 
                field: "email",
                title: "Email",
                editor: function(container, options){
                    var input = $('<input type="email" data-email-msg="Invalid email!" class="k-textbox" required/>');
                    input.attr("name", options.field);
                    input.appendTo(container);
                }
            },
            { command: ["edit", "destroy"], title: "Operations", width: "240px" }
        ],
        editable: "popup"
    });
</script>

应使用验证属性添加到列定义自定义编辑器:

{
    field: "email",
    title:"Email",
    editor: function(container, options) {
        var input = $('<input type="email" data-email-msg="Invalid email!" class="k-textbox"/>');
        input.attr("name", options.field);
        input.appendTo(container);
    }
}

更新:电话验证:将此属性添加到电话输入("Phonerule" - 是自定义验证规则的名称):

data-phonerule-msg="Invalid phone!"

将自定义验证规则添加到schema.model.fields.phone

phone: {
    type: "string",
    validation: {
        phonerule: function(e) {
            if (e.is("[data-phonerule-msg]"))
            {
                var input  = e.data('kendoMaskedTextBox');
                return input.value().indexOf(input.options.promptChar) === -1;
            }
            return true;
        }
    }
}

您可以使用此代码添加移动和电子邮件验证 -

schema: {
        model: {
            id: "id",
            fields: {                   
                mobile: {
                    editable: true, validation: {
                        required: true,
                        Mobilevalidation: function (input) {
                            if (input.is("[name='mobile']")) {
                                if ((input.val()) == "") {
                                    input.attr("data-Mobilevalidation-msg", "Mobile number required");
                                    return /^[A-Z]/.test(input.val());
                                }
                                else {
                                    if (/^'d+$/.test(input.val())) {
                                        if (input.val().length == 10) {
                                            return true;
                                        } else {
                                            input.attr("data-Mobilevalidation-msg", "Mobile number is invalid");
                                            return /^[A-Z]/.test(input.val());
                                        }
                                    }
                                    else {
                                        input.attr("data-Mobilevalidation-msg", "Mobile number is invalid");
                                        //alert(/^[A-Z]/.test(input.val()));
                                        return /^[A-Z]/.test(input.val());
                                    }
                                    return true;
                                }
                            }
                            return true;
                        }
                    }
                },
                email: { editable: true, type: "email", validation: { required: true } },
            }
        }
    }