I have a kendo grid that needs to display discounts.I have to implement the validation that it should accept numbers between 0.00 and 100. I have written code for accepting numbers between 0 and 100, now i need to implement the 2 decimal place validation as well. Please help.
$(gridname).kendoGrid({
dataSource: {
data: data.ReportData,
schema: {
model: {
fields: {
ProposedDiscountNST: {format: "{0:n2}",
validation: {
required: true,
proposeddiscountNSTvalidation: function (input) {
if (input.val() != "" && input.is("[name='ProposedDiscountNST']")) {
input.attr("data-proposeddiscountNSTvalidation-msg", "Should be between 0.00 & 100");
// return input.val() >= 0 && input.val() < 101 && input.val() % 1 == 0;
return input.val() >= 0 && input.val() < 101 ; // Accepts max 2 decimal digits
} else {
return true;
}
}
}
}
I need to display the validation message that this field accepts 2 decimal places only. Please help.
How to obtain the number of decimals is described in multiple places, e.g. Simplest way of getting the number of decimals in a number in JavaScript Get this number and check if is okay or not.
One remark: You are checking if input.val() < 101 This includes 100.7 and does not seem match your requirement "between 0.00 and 100".
You can get the number of decimals by comparing the number and the fixed number (number.toFixed(x) rounds the given number to x decimals):
$(gridname).kendoGrid({
dataSource: {
data: data.ReportData,
schema: {
model: {
fields: {
ProposedDiscountNST: {format: "{0:n2}",
validation: {
required: true,
proposeddiscountNSTvalidation: function (input) {
if (input.val() != "" && input.is("[name='ProposedDiscountNST']")) {
input.attr(
"data-proposeddiscountNSTvalidation-msg",
"Value should be between 0.00 & 100 and have a maximum of 2 decimals"
);
return
input.val() >= 0 &&
input.val() <= 100 &&
input.val() == input.val().toFixed(2)
;
} else {
return true;
}
}
}
}
}
}
}
}
});
Actually I tried the above solution by Stephan T. but unfortunately it did not work. so I tried this method and it worked. So posting it so that it will help some one.
$(gridname).kendoGrid({
dataSource: {
data: data.ReportData,
schema: {
model: {
fields: {
ProposedDiscountNST: {format: "{0:n2}",
validation: {
required: true,
proposeddiscountNSTvalidation: function (input) {
if (input.val() != "" && input.is("[name='ProposedDiscountNST']")) {
input.attr("data-proposeddiscountNSTvalidation-msg", "Should be between 0.00 & 100");
// return input.val() >= 0 && input.val() < 101 && input.val() % 1 == 0;
return input.val() >= 0 && input.val() <= 100 && ((parseFloat(input.val()) / (parseFloat(input.val()).toFixed(2))) == 1 ); // Accepts max 2 decimal digits
} else {
return true;
}
}
}
}
Related
I am using kendo grid to display data, but while sorting(ascending or descending) it's sorting perfectly for string values. But for numeric it's not sorting properly it's taking only first character to do sorting, not taking as string values even it's in numeric. How to solve this issue ?
You can use the gird column sortable.compare property to assign your own compare function.
Then what you are looking for is a Natural sort, like the one described here: http://web.archive.org/web/20130826203933/http://my.opera.com/GreyWyvern/blog/show.dml/1671288 and implemented here: http://www.davekoelle.com/files/alphanum.js
Here is a demo using a case insensitive version of the natural sort:
https://dojo.telerik.com/eReHUReH
function AlphaNumericCaseInsensitive(a, b) {
if (!a || a.length < 1) return -1;
var anum = Number(a);
var bnum = Number(b);
if (!isNaN(anum) && !isNaN(bnum)) {
return anum - bnum;
}
function chunkify(t) {
var tz = new Array();
var x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >= 48 && i <= 57));
if (m !== n) {
tz[++y] = "";
n = m;
}
tz[y] += j;
}
return tz;
}
var aa = chunkify(a ? a.toLowerCase() : "");
var bb = chunkify(b ? b.toLowerCase() : "");
for (x = 0; aa[x] && bb[x]; x++) {
if (aa[x] !== bb[x]) {
var c = Number(aa[x]), d = Number(bb[x]);
if (!isNaN(c) && !isNaN(d)) {
return c - d;
} else return (aa[x] > bb[x]) ? 1 : -1;
}
}
return aa.length - bb.length;
}
var dataSource = new kendo.data.DataSource({
data: [
{ id: 1, item: "item101" },
{ id: 2, item: "item2" },
{ id: 3, item: "item11" },
{ id: 4, item: "item1" }
]
});
$("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
columns: [{
field: "item",
sortable: {
compare: function(a, b) {
return AlphaNumericCaseInsensitive(a.item, b.item);
}
}
}]
});
I have a kendo grid with save button in the Tool bar panel. I have a proposed discount column which is editable and if the user enters whole numbers between 0 and 100(excluding decimals) , the save button should be visible or enabled otherwise invisible or disabled. I was able to achieve making the button invisible or disable but when they enter correct value, the button was not getting visible or enabled. Please help me. I just started working on Kendo UI recently.
function setEnabled(enabled) {
if (enabled) {
// $(".k-grid-nstToolbarBtn").removeClass("k-state-disabled");
$(".k-grid-nstToolbarBtn").show();
}
else {
// $(".k-grid-nstToolbarBtn").addClass("k-state-disabled");
$(".k-grid-nstToolbarBtn").removeAttr("href");
$(".k-grid-nstToolbarBtn").hide();
}
}
$('#NSTGrid').kendoGrid({
toolbar: [{ type: "button", text: "Save", name: "nstToolbarBtn", className: "k-grid-saveData" }],
dataSource: {
data: data.ReportData,
schema: {
model: {
fields: {
ProposedDiscount: {
validation: {
required: true,
proposeddiscountvalidationcvalidation: function (input) {
if (input.val() != "" && input.is("[name='ProposedDiscount']")) {
input.attr("data-proposeddiscountvalidationcvalidation-msg", "Proposed Discount should be whole number");
setEnabled(false);
return input.val() >= 0 && input.val() < 101 && input.val() % 1 == 0;
} else {
setEnabled(true);
return true;
}
}
}
},
ProductApprovedDiscount: { type: "decimal", editable: false },
BAN: { type: "string", editable: false },
I think the value passed to your setEnabled function needs to be the same as what you return as the validation result. Please try the following change:
proposeddiscountvalidationcvalidation: function (input) {
if (input.val() != "" && input.is("[name='ProposedDiscount']")) {
input.attr("data-proposeddiscountvalidationcvalidation-msg", "Proposed Discount should be whole number");
var valid = input.val() >= 0 && input.val() < 101 && input.val() % 1 == 0;
setEnabled(valid);
return valid;
} else {
return true;
}
}
I have a kendo grid where i need the user to enter only whole numbers between 0 to 100 to Proposed Discount Column(only editable column in the grid). Even if the user enters the correct value,it shows the error message.
fields: {
ProposedDiscount: {
validation: {
required: true,
proposeddiscountvalidation: function (input) {
if ((input.val() >= 0 && input.val() < 101) && input.is("[name='ProposedDiscount']")) {
input.attr("data-proposeddiscountvalidation-msg", "Proposed Discount should be whole number");
return false;
} return true;
}
}
}
The error i am getting on the ui.
I am new to Kendo UI.
Consider the following code i want to set the grid datePicker column empty if date validation fails WorkOrderDate< task date , any help would be higly appreciable.
***********Grid***************
columns.Bound(c => c.WorkOrderDetailsDate)
.Title("Estimated Start Date")
.EditorTemplateName("WorkOrderDetailsDate")
***********Editor**************
#model DateTime?
#(Html.Kendo().DatePicker()
.Name("WorkOrderDetailsDate")
.Value(Model == null ? DateTime.Now.Date : ((DateTime)#Model).Date)
.Events(d=>d.Change("TaskDateValidate"))
)
*************JavaScript***********
function TaskDateValidate(e)
{
if ($("#workOrder_EstStartDate").val() != null && $("#workOrder_EstStartDate").val() != "") {
var workDate = kendo.parseDate($("#workOrder_EstStartDate").val());
var taskDate = kendo.parseDate(kendo.toString(this.value(), 'd'));
if (taskDate < workDate)
{
showMessage("Task date should be after work order Date");
this.value(""); <-----this is not working want to set to empty to force user to select date again
this.value("28/02/2014");<---this is not working as well...
}
}
}
please advise on this problem
reagrds
Shaz
found the solution my self...
//Add validation on Grid
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: {
greaterdate: function (input) {
if (input.is("[data-val-greaterdate]") && input.val() != "") {
var date = kendo.parseDate(input.val()),
earlierDate = kendo.parseDate($("[name='" + input.attr("data-val-greaterdate-earlierdate") + "']").val());
return !date || !earlierDate || earlierDate.getTime() < date.getTime();
}
return true;
},//end of greaterdate
shorterdate: function (input) {
if (input.is("[data-val-shorterdate]") && input.val() != "") {
var date = kendo.parseDate(input.val()),
laterDate = kendo.parseDate($("[name='" + input.attr("data-val-shorterdate-laterdate") + "']").val());
return !date || !laterDate || laterDate.getTime() > date.getTime();
}
return true;
},//end of shorter date
// custom rules
taskdate: function (input, params) {
if (input.is("[name=WorkOrderDetailsDate]")) {
//If the input is StartDate or EndDate
var container = $(input).closest("tr");
var tempTask = container.find("input[name=WorkOrderDetailsDate]").data("kendoDatePicker").value();
var tempWork = $("#workOrder_EstStartDate").val();
var workDate = kendo.parseDate(tempWork);
var taskDate = kendo.parseDate(tempTask);
if (taskDate < workDate) {
return false;
}
}
//check for the rule attribute
return true;
}
}, //end of rule
messages: {
greaterdate: function (input) {
return input.attr("data-val-greaterdate");
},
shorterdate: function (input) {
return input.attr("data-val-shorterdate");
},
taskdate: function (input) {
return "Task date must be after work date!";
},
}
});
})(jQuery, kendo);
I use jQuery Validation plugin to ensure what user entered positive cost_of_car in first text field and positive payment_amount in second text field such what *cost_of_car * 0.4 <= payment_amount <= cost_of_car*:
$.validator.addMethod("testMaxAmount", function()
{
return $("#cost_of_car").val() - 0 >= $("#payment_amount").val() - 0;
}, "Can't be more than cost_of_car");
$.validator.addMethod("testMinAmount", function()
{
return $("#cost_of_car").val() * 0.4 <= $("#payment_amount").val() - 0;
}, "Can't be less than cost_of_car * 0.4");
$("#calc_form").validate(
{
rules:
{
cost_of_car:
{
required: true,
number: true,
min: 1,
max: 10000000
},
payment_amount:
{
required: true,
number: true,
testMaxAmount: true,
testMinAmount: true
}
}
});
Now I want to skip testMaxAmount and testMinAmount checks until cost_of_car is valid. Testing
$("#calc_form").validate().element("#cost_of_car")
or even
$("#calc_form").validate({ignore: "#payment_amount"}).element("#cost_of_car")
inside these methods leads to the recursion and hangs browser.
Would you propose some other method to disable validation of payment_amount until cost_of_car is valid, please?
UPDATE: The change has to be in the validator.addMethod() calls:
$.validator.addMethod("testMaxAmount", function()
{
if($("#cost_of_car").valid())
return $("#cost_of_car").val() - 0 >= $("#payment_amount").val() - 0;
else
return true;
}, "Can't be more than cost_of_car");
$.validator.addMethod("testMinAmount", function()
{
if($("#cost_of_car").valid())
return $("#cost_of_car").val() * 0.4 <= $("#payment_amount").val() - 0;
else
return true;
}, "Can't be less than cost_of_car * 0.4");