Use Custom Validation in Filter Menus
Environment
Product | Progress® Kendo UI® Grid for jQuery |
Operating System | All |
Browser | All |
Browser Version | All |
Description
How can I use custom validation in the filter menu of the jQuery Grid by Kendo when the filtering functionality is applied?
Solution
Your project might require you to validate the user input in the filtering user interface (UI) generated by the Grid in its Filter menu.
For example, by using the Kendo UI DatePicker for date fields or the Kendo UI NumericTextBox for numeric fields.
To achieve this behavior:
- Handle the
filterMenuInit
event and get a reference to the corresponding widgets. - Get a reference to the built-in Kendo UI Validator.
- Use the
rules
andmessages
options of the Validator to add the necessary custom validation logic and messages.
As a result, when the user input does not follow the predefined rules, the custom validation will be triggered.
The following example demonstrates how to use custom validation in the Filter menu of the Grid when the filtering functionality is applied.
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "date", format: '{0:MM/dd/yyyy}' },
{ field: "age" }
],
dataSource: {
data: [
{ name: "Jane Doe", date: new Date(2016, 10, 15), age: 25},
{ name: "John Doe", date: new Date(2016, 10, 17), age: 20}
],
schema: {
model: {
fields: {
date: {
type: 'date'
},
age: {
type: 'number'
}
}
}
}
},
filterable: true,
filterMenuInit: function(e) {
if (e.field === "date" || e.field === 'age') {
e.container.find("[data-role=datepicker]").each(function(idx) {
$(this).attr("name", "date" + idx);
$('<span class="k-invalid-msg" data-for="' + "date" + idx + '"></span>')
.insertAfter($(this).closest(".k-datepicker"));
});
e.container.find("[data-role=numerictextbox]").each(function(idx) {
$(this).attr("name", "date" + idx);
$('<span class="k-invalid-msg" data-for="' + "date" + idx + '"></span>')
.insertAfter($(this).closest(".k-numerictextbox"));
});
e.container.kendoValidator({
rules: {
datePickers: function(input){
var dtp = input.data('kendoDatePicker');
if(dtp && input.val()){
return !!dtp.value() ;
}
return true;
},
numerics: function(input){
var ntb = input.data('kendoNumericTextBox');
if(ntb && input.val()){
return !!(ntb.value() > 0);
}
return true;
}
},
change: function() {
var button = e.container.find(".k-primary");
this.value() ? button.removeAttr("disabled") : button.prop("disabled", "disabled")
},
messages: {
datePickers: "Please enter a valid date",
numerics: "Age must be > 0"
}
});
}
}
});
</script>