Validation on edit popup window of KendoUI grid with editor templates

13 posts, 0 answers
  1. Jennifer
    Jennifer avatar
    4 posts
    Member since:
    May 2012

    Posted 15 Mar 2013 Link to this post


    Hi,

    I am using the popup editing feature of the grid. Now I need to put some validation in. I was able to figure out how to validate the string field but can't figure out how to validate the date fields since I am usingt the DateTimePicker on the popup window (code at bottom).
    I would like to validate that the days are greeater than today and that EndDate > StartDate for example.

    Thanks in advance.

    jennifer

    var AuctionGrid = {};
      
    /// class variables
    AuctionGrid._id = null;
    AuctionGrid._auctionDataSource = null;
      
    /// <summary>Initialize the auctions grid</summary>
    AuctionGrid.init = function () {
      
        // Auction Datasource
        AuctionGrid._auctionDataSource = new kendo.data.DataSource({
            transport: {
                read: {
                    url: _rootUrl + "Test/GetAuctions/"
                },
                update: {
                    url: _rootUrl + "Test/UpdateAuctions/",
                    type: "POST"
                },
                destroy: {
                    url: _rootUrl + "Test/DestroyAuction/",
                    type: "POST"
                },
                create: {
                    url: _rootUrl + "Test/CreateAuction/",
                    type: "POST"
                },
                parameterMap: function (data, type) {
                    // If update, create or destroy, then serialize the data
                    // as JSON so that it can be more easily read on the server.
                    if (type != "read") {
                        return { models: JSON.stringify(data.models) };
                    } else {
                        return data;
                    }
                }
            },
            schema: {
                model: {
                    id: "AuctionID",
                    fields: {
                        AuctionID: {
                            editable: false,
                            type: "number"
                        },
                        AuctionName: {
                            type: "string",
                            validation: {
                                required: { message: "An Auction Name is Required!" },
                                validateAuctionName: function (input) {
                                    //alert(input.attr("data-bind"));
                                    if (input.attr("data-bind") == "value:AuctionName") { // check if this is the element to validate
                                        alert(input.val().length);
                                        if (input.val().length > 10) {
                                            input.attr("data-validateAuctionName-msg", "AuctionName can only have a maximum of 10 characters.");
                                            return false;
                                        }
                                        else
                                            return true;
                                    }
                                    return true;
                                }
                            }
                        },
                        ShortDescription: {
                            type: "string"
                        },
                        LongDescription: {
                            type: "string"
                        },
                        StartDate: {
                            type: "date"
                        },
                        EndDate: {
                            type: "date",
                            validation: {
                                required: { message: "End Date is Required!" },
                                validateEndDate: function (input) {
                                      
                                        HOW DO I USE VALIDATION HERE - HOW DO I VALIDATE THAT END DATE > START DATE  
                                }
                            }
                        },
                        Active: { type: "boolean" }
                    }
                }
            }
        });
      
      
        // Display the active auctions in a kendo grid.
        $("#AuctionGrid").kendoGrid({
            dataSource: AuctionGrid._auctionDataSource,
            scrollable: true,
            editable: "popup",
            pageSize: 6,
            edit: onEdit,
            height: 300,
            toolbar: ["create"],
            columns: [{
                field: "AuctionName",
                title: "Auction Name",
                width: "200px"
            }, {
                field: "ShortDescription",
                title: "Description",
                editor: textareaEditor
            }, {
                field: "StartDate",
                title: "Start Date",
                format: "{0:MM-dd-yyyy hh:mm tt}",
                editor: dateTimeEditor,
                width: "100px"
            }, {
                field: "EndDate",
                title: "End Date",
                format: "{0:MM-dd-yyyy hh:mm tt}",
                editor: dateTimeEditor,
                width: "100px"
            }, {
                field: "Active",
                title: "Active",
                template: "<input type=\"checkbox\" />",
                width: "80px"
            }, {
                command: ["edit", "destroy"], title: " ", width: "110px"
            }],
            groupable: false
        });
      
    }
      
    function onEdit(e) {
        $(e.container).parent().css({
            width: '600px',
            height: '400px'
        });
        // set maxLengths
        e.container.find("input[name=AuctionName]").attr("maxlength", 10);
    }
      
    function dateTimeEditor(container, options) {
      
        $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
                    .appendTo(container)
                    .kendoDateTimePicker({});
    }
      
    function textareaEditor(container, options) {
      
        $('<textarea data-bind="value:' + options.field + '" style="width:400px;" rows="4" ></textarea>')
            .appendTo(container);
    }
  2. Vladimir Iliev
    Admin
    Vladimir Iliev avatar
    2172 posts

    Posted 19 Mar 2013 Link to this post

    Hi Jenifer,

     
    Basically you should attach kendoValidator and define your custom validation rules for these fields - please check the example below:

    //Custom validation
            $("#grid").kendoValidator({
                rules: {
                    // custom rules
                    custom: function (input, params) {
                        if (input.is("[name=StartDate]") || input.is("[name=EndDate]")) {
     
                            //If the input is StartDate or EndDate
                            var container = $(input).closest("tr");
     
                            var start = container.find("input[name=StartDate]").data("kendoDatePicker").value();
                            var end = container.find("input[name=EndDate]").data("kendoDatePicker").value();
     
     
                            if (start > end) {
                                return false;
                            }
                        }
                        //check for the rule attribute
                        return true;
                    }
                },
                messages: {
                    custom: function (input) {
                        // return the message text
                        return "Start Date must be greater than End Date!";
                    }
                }
            })

    For more information about the validator I would suggest to check the validator API and the validator overview guide. 
     
    Kind Regards,
    Vladimir Iliev
    the Telerik team
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
  3. Kendo UI is VS 2017 Ready
  4. Will
    Will avatar
    34 posts
    Member since:
    Oct 2013

    Posted 09 Mar 2015 Link to this post

    I tried the code above and when I changed one of the dropdownlists in my popup editor, the validator's "input" was the (nameless) pageSizes selector of the grid itself.

    outerHTML   "<select style=\"display: none;\" data-role=\"dropdownlist\"><option selected=\"selected\" value=\"10\">10</option><option value=\"20\">20</option><option value=\"40\">40</option><option value=\"80\">80</option></select>"
  5. Will
    Will avatar
    34 posts
    Member since:
    Oct 2013

    Posted 09 Mar 2015 in reply to Will Link to this post

    Just to follow up, my popup uses a template enclosed in a div with an id="popupContainer".

    This worked for me:

    popupValidator = $("#popupContainer").kendoValidator({
        rules: {
            companyIDRule: function (input) {
                var result = true;
                if (input.is("[name=CompanyIDSelect]")) {
                    if (!input.val()) {
                        result = false;
                    } else if (input.val() <= 0) {
                        result = false;
                    }
                }
                return result;
            }
        }
        , messages: {
            companyIDRule: "Comparison Operator is not compatible with the number of CompanyID values specified. Eg. 'Equals' should correspond to a single value."
        }
    }).data("kendoValidator");
  6. Vladimir Iliev
    Admin
    Vladimir Iliev avatar
    2172 posts

    Posted 09 Mar 2015 Link to this post

    Hello Will,

    With current version of Kendo UI you can now define the desired custom validation rules directly in the "dataSource.schema.model.fields.rules" option as described below:

    var dataSource = new kendo.data.DataSource({
      schema: {
        model: {
          id: "ProductID",
          fields: {
            ProductID: {
              editable: false,
              nullable: true
            },
            StartDate: {
              type: "date",
              validation: {
                required: true,
                customValidation: function(input, params) {
                  if (input.is("[name=StartDate]")) {
                     
                    var date = $(input).data("kendoDatePicker").value();
                     
                     
                    if (date > new Date()) {
                      return false;
                    }
                  }
                  //check for the rule attribute
                  return true;
                }
              }
            }
          }
        }
      },


    Regards,
    Vladimir Iliev
    Telerik
     
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
     
  7. Will
    Will avatar
    34 posts
    Member since:
    Oct 2013

    Posted 09 Mar 2015 in reply to Vladimir Iliev Link to this post

    Hello Vladimir,

    Thank you for your suggestion.  When I tried that approach, the rule is called but the "input" parameter always has a length of 0.  So, no name and no value.

    Taking a rule directly from your Demos:

    CompanyIDValue: {
                        nullable: true
                        ,validation: {
                            wakavalid: function (input) {
                                if (input.is("[name='CompanyIDValue']") && input.val() != "") {
                                    input.attr("data-productnamevalidation-msg", "Product Name should start with capital letter");
                                    return /^[A-Z]/.test(input.val());
                                }
                                return true;
                            }
                        }
                    },


    Will Dougherty
  8. Will
    Will avatar
    34 posts
    Member since:
    Oct 2013

    Posted 09 Mar 2015 in reply to Will Link to this post

    By the way, while the Kendo UI documentation has improved tremendously over the last year or two, this area is still weakly described.  Or maybe I just haven't found the right place.  If you go to the API document for DataSource, it trails off at Model.  If you go to the API document for Model, it does not even mention rules or validation.
  9. Vladimir Iliev
    Admin
    Vladimir Iliev avatar
    2172 posts

    Posted 09 Mar 2015 Link to this post

    Hello Will,

    I tried to reproduce the problem locally but to no avail – everything is working as expected on our side. Could you please check the example below and let us know how it differs from your real setup?

    Regards,
    Vladimir Iliev
    Telerik
     
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
     
  10. Will
    Will avatar
    34 posts
    Member since:
    Oct 2013

    Posted 09 Mar 2015 in reply to Vladimir Iliev Link to this post

    Hi Vladimir,
    I have spent a bit of time decomposing my somewhat involved example to the point between working and not working.
    What I found is that when I'm specifying an popup editor template, I lose the input.
    I have simplified my Model and the template down to the absolute minimum to eliminate complicating factors and still that's what I'm seeing.

    The template is simple:
    <!-- popup editor template -->
        <script id="popup_editor_template" type="text/x-kendo-template">
            <div id="popupContainer">
     
                <div class="k-edit-label">
                    <label for="referenceNumber">Ref \\#</label>
                    <span data-bind="text: CarrierCommissionRuleID"></span>
                </div>
     
                <div class="k-edit-label">
                    <label for="CompanyIDSelect">Company ID: </label>
                    <input id="companyIDComparisonOperator" name="CompanyIDComparisonOperator" data-bind="value: CompanyIDComparisonOperatorID" />
                </div>
            </div>
        </script>


    And the schema/model:
    schema: $.extend(true, {}, kendo.data.schemas["aspnetmvc-ajax"], {
        data: "Data",
        total: "Total",
        errors: "Errors",
        model: {
            id: "CarrierCommissionRuleID",
            fields: {
                CarrierCommissionRuleID: { type: "number", editable: false },
                CompanyIDComparisonOperatorDisplay: {
                    type: "string", nullable: true, validation: {
                        wakavalid: function (input, params) {
                            if (input.is("[name='CompanyIDValue']") && input.val() != "") {
                                input.attr("data-productnamevalidation-msg", "Product Name should start with capital letter");
                                return /^[A-Z]/.test(input.val());
                            }
                            return true;
                        }
                    }
                }
            }
        }
    })


    Sorry but I haven't learned jsFiddle yet and I tried unsucessfully to modify your example to test with it.

    Any suggestions?

    Will
  11. Vladimir Iliev
    Admin
    Vladimir Iliev avatar
    2172 posts

    Posted 10 Mar 2015 Link to this post

    Hello Jennifer,

    From the provided code it seems that the validation is looking for input with "name" attribute equal to "CompanyIDValue", however the editor template doesn't have such editor. Could you please update the editor template / validation function to search for editors that are available and let us know of the result? 

    Also for convenience I updated the previous example to use custom editor: Regards,
    Vladimir Iliev
    Telerik
     
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
     
  12. Will
    Will avatar
    34 posts
    Member since:
    Oct 2013

    Posted 10 Mar 2015 in reply to Vladimir Iliev Link to this post

    Hi Vladimir,

    I did as you suggested but it did not change the results.

    What I am seeing is that when I do NOT use the editor template, my "input" parameter looks like this:
    _proto: {...}
    context: {...}
    length: 1
    selector: ""
    [0]: {...}

    When I do use the editor template, my "input" parameter looks like this:
    _proto: {...}
    context: {...}
    length: 0
    selector: ""

    So, the name I'm specifying is not relevant, there is simply NO information available, no name at all. 

    I'm working on a small example project that I can send to you guys to demonstrate.  Would it be better to continue working through the forum or to open a Support Ticket?

    Will
  13. Vladimir Iliev
    Admin
    Vladimir Iliev avatar
    2172 posts

    Posted 10 Mar 2015 Link to this post

    Hi Will,

    It seems that the described behavior is related to the current setup that you have - that why I would ask you to open a new support ticket (as you suggested) and provide the example where the issue is reproduced. In this way it is much easier to follow and concentrate on the particular issue which usually leads to its faster resolving.

    Regards,
    Vladimir Iliev
    Telerik
     
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
     
  14. Will
    Will avatar
    34 posts
    Member since:
    Oct 2013

    Posted 16 Mar 2015 in reply to Vladimir Iliev Link to this post

    Just to follow up, I did open a Support Ticket.

    Support ID:916107 -- Validator is called with no "input" when in Grid popup editor using a template.

    "For performance reasons, the editor will search for inputs only with value binding without space:"

    In my template's data-bind="value:..." declarations, I had a space after the colon, value: Name vs. value:Name. 

    I REALLY don't like the answer but I'm very happy to have it.

    Will
Back to Top
Kendo UI is VS 2017 Ready