A simple question, or so I thought.
How to disable client side validation for kendo mvc grid?
I thought there would be a property: "Enabled", "validator" or such which I could set to false but I can't find nothing.
You're correct in that there's no way to disable the validation via a property or options setting, however, you can work around it.
The validators for the grid cells are created internally by the grid. You can disable validation by replacing the functions of the validator object in the "edit" event of the grid, after it is created, i.e.:
edit: function (e) {
// Always return valid
e.sender.editable.validatable.validate = function () { return true; };
e.sender.editable.validatable.validateInput = function(input) { return true; };
}
This should have the effect of disabling validation by always returning true.
EDIT:
You might also want to replace validateInput, I've updated the code snippet.
Related
I am using kendo controls for my project. I was using jquery validation to validate my controls at client side but as jquery validation is not working for kendo controls so I am using kendo validators to validate the controls.
I am using dataannotation validation with MVC 5 project. Here is sample dojo.
It is working perfect but the validation only appear on focus-out or blur event. Is there any way to validate control on change of value of control like jquery validation?
Update:
Here is the complete solution that helped me to resolve this issue:
if ($.validator !== undefined) {
$.validator.setDefaults({
ignore: [],
highlight: function (element, errorClass) {
element = $(element);
var highLightElement;
if (element.parent().hasClass("k-picker-wrap") ||
element.parent().hasClass("k-numeric-wrap")) {
highLightElement = element.parent().parent();
}
else if (element.parent().hasClass("k-widget")) {
highLightElement = element.parent();
} else if (element.parent().children('.k-upload-empty').length > 0) {
highLightElement = $(element.parent().children('.k-upload-empty')[0]);
} else {
highLightElement = element;
}
highLightElement.addClass('input-validation-error');
},
unhighlight: function (element, errorClass) {
element = $(element);
var highLightElement;
if (element.parent().hasClass("k-picker-wrap")
|| element.parent().hasClass("k-numeric-wrap")) {
highLightElement = element.parent().parent();
}
else if (element.parent().hasClass("k-widget")) {
highLightElement = element.parent();
} else {
highLightElement = element;
}
highLightElement.removeClass('input-validation-error');
}
});
}
You have 2 ways to meat your purpose:
Using jQuery Unobtrusive Validation with KendoUI
Background
As you know the Kendo UI Editor creates a different elements than HTML form elements. Other JavaScript editors work in a similar fashion. The actual HTML is hidden using CSS (display: none;), and therein lies the issue. By default jQuery Validation ignores hidden input fields. There are validation data-* attributes on the form elements, but since it is hidden, when the unobtrusive validation fires, the editor is ignored.
Solution
You have 2 ways to solve this issue and perfectly work with both technologies. Read the Making the Kendo UI Editor Work With jQuery Validations and if you have any problem for implementing, please read Kendo UI NumericTextBox With jQuery Validation as an example for NumericTextBox
Then, You may have problem to assign proper CSS class in case of validation. You can read adding jquery validation to kendo ui elements.
Just using KendoUI Validators
You should implement desired event for the validation purpose. Here you need onChange event to work like jQuery Unobtrusive Validation. Use the following code as it describes what to do:
$(document).ready(function () {
function widgetChange() {
//place validation logic
};
$("#dropdownlist").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
change: widgetChange
});
})
You may want to use both of them! So take a look at .Net Mvc 3 Trigger (other than submit button) Unobtrusive Validation
Update
A dojo for implementing with last solution which added a pattern="\d+" to search input with a validation message. The validation is called by filtering event for the same input. Note that you should use desired event based on UI element, here we used filtering for autocomplete instead of using change for DropDownList.
I recently found a new implementation which is looking good to try and test. That is available at aspnet-mvc getting-started validation
In the ASP MVC page I'm currently working on, the values of three input fields determine the value of a fourth. Zip code, state code, and something else called a Chanel Code will determine what the value of the fourth field, called the Territory Code, will be.
I just started learning jQuery a couple weeks ago, so I would first think you could put a .change event that checks for values in the other two fields and, if they exists, call a separate method that compares the three and determines the Territory code. However, I'm wondering if there is a more elegant way to approach this since it seems like writing a lot of the same code in different places.
You can bind a callback to multiple elements by specifying multiple selectors:
$(".field1, .field2, .field3").click(function() {
return field1 +
field2 +
field3;
});
If you need to perform specific actions depending on which element was clicked, another option would be to create a function which performs the actual computation and then invoke that from each callback.
var calculate = function() {
return field1 +
field2 +
field3;
};
And then invoke this function when on each click:
$(".field1").click(function() {
// Perform field1-specific logic
calculate();
});
$(".field2").click(function() {
// Perform field2-specific logic
calculate();
});
// etc..
This means that you do not repeat yourself.
This works for me
jQuery(document).on('scroll', ['body', window, 'html', document],
function(){
console.log('multiple')
}
);
Adding another possibility, just in cased this may help someone. This version should work on dynamically created fields.
$("#form").on('change', '#Field1, #Field2, #Field3', function (e) {
e.preventDefault();
console.log('something changed');
});
I have a KendoUI Grid I'm using an MVC web application, all working fine however I want to add a custom command button that is shown conditionally in the UI and simply executes a command on my controller passing it the required parameter.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click())
The command is specified as above but I only want the button to show when the DataItems IsLocked property is true.
I also cannot figure out how to just call and method on the controller rather. I cannot find a demo of this on the Kendo site and not sure how to move this forward.
Here is a specific example for using client templates for conditional command buttons.
const string ShowUpdateButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-edit' href='\\#'><span class='k-icon k-edit'></span>Update</a>#}#";
const string ShowReverseButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-reverse' href='/JournalDetail/Reverse/#: ID #' ><span class='k-icon k-reverse'></span>Reverse</a>#}#";
const string ShowDeleteButton = "#if (IsAdjustment == true) {#<a class='k-button k-button-icontext k-grid-delete' href='\\#'><span class='k-icon k-delete'></span>Delete</a>#}#";
You can do the template inline but I find it easier (particularly for multiple buttons) if you declare constants and then use string.format to concatenate them.
col.Template(o => o).ClientTemplate(string.Format("{0}{1}{2}", ShowUpdateButton, ShowDeleteButton, ShowReverseButton));
The upside is it will work with popup editor whereas jquery hacks will ignore the conditional status when a user cancels out of edit. A cancel from the popup editor will restore the grid row from the viewmodel or wherever Kendo stores it which results in button states from before any jquery/javascript hack. The method above will also auto-wire the standard commands since I copied their HTML output for the client template.
The downside is that if Kendo changes their pattern for command buttons the client template may fail. I tired several other methods besides this one and the downside to this method seems better than the other methods.
Note on Kendo Forums: As of the date of this post, they do not appear to allow people who do not pay for support to post to the forums so I would suggest posting questions here instead. They monitor Stack Overflow and in my experience they seem to answer questions more quickly here.
Use template column instead - via the ClientTemplate method.
Conditional templates are covered here and multiple times on the forums - the Command columns is not that flexible.
As of the December 2018 release of Kendo, you can now conditionally display custom buttons more easily, but it still relies on JavaScript to do its work, this function should be defined before your dataGrid or you'll run into issues.
function showCommand(dataItem) {
console.log("determining to hide or show" + dataItem);
// show the Edit button for the item with Status='New'
if (dataItem.Status == 'New') {
return true;
}
else {
return false;
}
}
Then the code for the Grid.
.Columns (columns => {
columns.Command (
command => command.Custom ("Approve")
.Visible ("showCommand")
.Click ("approveFunc")
)
.Width (100)
.HeaderTemplate ("Actions")
})
You can control custom command button visibility by Visible property.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click().Visible("unlockAccountVisible"))
Visible property accepts JS function name and passes current dataItem as an argument.
JS function that evaluates button visibility:
<script>
function unlockAccountVisible(dataItem) {
// show the UnlockAccount button only when data item property IsLocked == true
return dataItem.IsLocked;
}
</script>
Read more in Show Command Buttons Conditionally kendo-ui documentation article.
I am using Knockout Js for my view page. I have a requirement where if any editable field changes, I have to enable Save button else not. This is working nicely.
My issue is I have checkboxes too for each row of item. These are observable items in my viewModel. What happens now is when I check or uncheck any checkbox, Knockout considers that as Dirty item and enables the Save button which I don't want.
How can I tackle this?
I am not sure of the exact code that you are using for a dirty flag, but if it involves using ko.toJS in a dependentObservable like this, then there is a trick that you can use to have it skip some observables.
If you create an observable that is a property of a function, then ko.toJS will not find it.
Here are two examples (someFlag and anotherFlag):
function Item(id, name) {
this.id = ko.observable(id);
//create a sub-observable that the dirty flag won't find
this.id.someFlag = ko.observable(false);
this.name = ko.observable(name);
this.dirtyFlag = new ko.dirtyFlag(this);
//or similarly, place an observable on a plain ol' function
this.forgetAboutMe = function() { };
this.forgetAboutMe.anotherFlag = ko.observable(false);
}
Sample here: http://jsfiddle.net/rniemeyer/vGU88/
I'm using the remote validation in MVC 3, but it seems to fire any time that I type something, if it's the second time that field's been active. The problem is that I have an autocomplete box, so they might click on a result to populate the field, which MVC views as "leaving" it.
Even apart from the autcomplete thing, I don't want it to attempt to validate when they're halfway through writing. Is there a way that I can say "only run validation n milliseconds after they are finished typing" or "only run validation on blur?"
MVC 3 relies on the jQuery Validation plugin for client side validation. You need to configure the plugin to not validate on key up.
You can switch it globally off using
$.validator.setDefaults({
onkeyup: false
})
See http://docs.jquery.com/Plugins/Validation/Validator/setDefaults and the onkeyup option here http://docs.jquery.com/Plugins/Validation/validate.
For future reference, I found it's possible to do this in combination with the typeWatch plugin (http://archive.plugins.jquery.com/project/TypeWatch).
Basically what you want to do is (in my case for a slug):
/*Disable keyup validation on focus and restore it to onkeyup validation mode on blur*/
$("form input[data-val-remote-url]").on({
focus: function () {
$(this).closest('form').validate().settings.onkeyup = false;
},
blur: function () {
$(this).closest('form').validate().settings.onkeyup = $.validator.defaults.onkeyup;
}
});
$(function () {
/*Setup the typeWatch for the element/s that's using remote validation*/
$("#Slug").typeWatch({ wait: 300, callback: validateSlug, captureLength: 5 });
});
function validateSlug() {
/*Manually force revalidation of the element (forces the remote validation to happen) */
var slug = $("#Slug");
slug.closest('form').validate().element(slug);
}
If you're using the vanilla typeWatch plugin, you'll have to setup a typeWatch for every element because the typeWatch callback doesn't give you access to the current element via $(this), it only passes the value.
Alternatively you can modify the typeWatch plugin to pass in the element (timer.el) and then you can apply a delay to all.
For some reason (maybe because of conflicts with the unobtrusive plugin), hwiechers' answer didn't work for me. Instead, I had to get the validator of my form with .data('validator') (as mentioned in this answer) and set onkeyup to false on it.
var validator = $('#form').data('validator');
validator.settings.onkeyup = false;
We had the same problem of focusing out the autocomplete textbox "DealingWithContactName" when autocomplete suggestion list pops up. Here we select the dynamically generated autocomplete list item on which the user clicks and set focus on to it. After 50ms we take the focus out from the textbox. It solved our problem.
$('body').on('click', 'ul.ui-autocomplete li a', function () {
$('#DealingWithContactName').focus();
window.setInterval(function () {
$('#DealingWithContactName').blur();
}, 50);
});
I wanted local validation to remain during onkeyup so that the user had a tighter feedback loop. This should only affect the remote validation (that results from RemoteAttribute):
$("[data-val-remote]").keyup(function () {
// Avoid hitting server validation during onkeyup. Wait for onfocusout.
return false;
});