3
votes

I'm using a Kendo Grid / Custom validator editing to validate the a Column in the grid,Actually I'm trying the check the email already exists in the database or not ? to implement it I would like to get ID for the Row.

For example given in reference its products table, so in this case I would to get the ProductID inside the validation function ?

Reference: http://demos.telerik.com/kendo-ui/grid/editing-custom-validation

2

2 Answers

3
votes

You can get the id by retrieving the uid and then getting the data item from the dataSource via dataSource.getByUid(). Each row in the grid has a unique uid generated by the grid.

So for instance, referring to kendo's demo, the validation would now look like this:

productnamevalidation: function (input) {
    //get row and uid
    var row = input.closest('tr')[0];
    var uid = $(row).attr('data-uid');

    //get data item and then its ProductID
    var dataitem = dataSource.getByUid(uid);
    console.log(dataitem);
    console.log(dataitem.ProductID);

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

    return true;
}

Here is their demo with this code included, you can open the console to see that each data row is being printed out with all its model properties.

2
votes

You can get the record's ID with this:

input[0].kendoBindingTarget.source.ID

For example:

emailUnique: function (input) {
    if (input.is("[name=Email]") && input.val() !== "") {
        input.attr("data-emailUnique-msg", "Email already exists");
        return isEmailUnique(input.val(), input[0].kendoBindingTarget.source.ID);
    }
    return true;
}

Bonus track, in case it's useful for someone:

function isEmailUnique(val, id) {
    var data = YourGridDataSource; // If you don't have it, you may need something like $("#YourGrid").data().kendoGrid.dataSource
    for (var i = 0; i < data.length; i++) {
        if (data[i].ID != id && data[i].Email == val)
            return false;
    }
    return true;
}