简体   繁体   English

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

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

Given the grid supplied in the code below, how do I set validation on the phone and email to take advantage of the validation and masked input features kendo provides on this page ( http://demos.telerik.com/kendo-ui/maskedtextbox/index )? 给定下面代码中提供的网格,我如何在电话电子邮件上设置验证以利用kendo在此页面上提供的验证和屏蔽的输入功能( http://demos.telerik.com/kendo-ui/maskedtextbox / index )?

For example, if the user types in 5628103322, it should format it as (562)810-3322 as the demo on their page shows. 例如,如果用户键入5628103322,则其格式应为(562)810-3322,如其页面上的演示所示。 Also if a number that was not entered correctly it should provide an error message. 另外,如果输入的数字不正确,则应该提供错误消息。

Same for email, how do we do this? 电子邮件也一样,我们该怎么做?

<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>

UPDATE:: 更新::

$("#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"
    });

the grid code above has changed, it almost works perfectly now thanks to the answer below, now I just need to figure out how to add validation to the phone number and email fields so input is required, and correct input. 上面的网格代码已更改,由于下面的回答,它现在几乎可以完美运行,现在我只需要弄清楚如何在电话号码和电子邮件字段中添加验证,因此需要输入并正确输入。

UPDATE #2 更新#2

The code below now works perfectly thanks to the answer, just wanted to share it to others that might need help. 现在,下面的代码非常完美,这要归功于答案,它只是想与其他可能需要帮助的人分享。 Something interesting to note is the model rule phonerule has to be named whatever the text in the middle between the dashes of this is data-phonerule-msg . 需要注意的是,模型规则电话规则必须命名为短划线中间的任何文本,即data-phonerule-msg I'm guessing Kendo-UI must look for that when looking for custom rules. 我猜想Kendo-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>

You should add to column definition custom editor with validation attributes: 您应将具有验证属性的列定义定制编辑器添加到:

{
    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);
    }
}

Update : phone validation: add this attribute to phone input ("phonerule" - is the name of custom validation rule): 更新 :电话验证:将此属性添加到电话输入(“ phonerule”-是自定义验证规则的名称):

data-phonerule-msg="Invalid phone!"

add custom validation rule to schema.model.fields.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;
        }
    }
}

You can use this code to add mobile and email validation - 您可以使用此代码添加手机验证和电子邮件验证-

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 } },
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM