Kendo UI: Displaying server-side errors using Kendo Validator - validation

I have a web form that does client validation using Kendo Validator. Once client validation succeeds the form values are sent to a web service that does additional validation and either saves the data or sends back a JSON object of error messages keyed by form field. These field names match the data-for attributes on the validator elements. Is there a way to display these errors using Kendo Validator?
I realize you can setup a custom rule to do server-side validation per field. This is about validating all the fields at once and displaying multiple errors.

You can display multiple errors using AddModelError method, as desribed in this topic http://blogs.telerik.com/kendoui/posts/13-08-29/handling-server-side-validation-errors-in-your-kendo-ui-grid#adding-server-side-vaildation

You can attach to response event and call function which show validation errors when some errors was returned from server.
Here is javascript section which can do it:
validationMessageTemplateForReplace = kendo.template(
'<div class="k-widget k-tooltip k-tooltip-validation k-invalid-msg field-validation-error" style="margin: 0.5em; display: block; " data-for="#=field#" data-valmsg-for="#=field#" id="#=field#_validationMessage">' +
'<span class="k-icon k-warning"> </span>#=message#<div class="k-callout k-callout-n"></div></div>');
function onResponseEnd(response) {
if (response.errors) onError(response.errors, $('#myForm'));
}
function onError(errors, element) {
for (var error in errors) {
addValidationMessage(element, error, errors[error].errors);
}
}
function addValidationMessage(container, name, errors) {
//add the validation message to the form
var found = container.find("[data-for=" + name + "],[data-val-msg-for=" + name + "],[data-valmsg-for=" + name + "]");
if (found.length > 0) {
found.replaceWith(bs.validationMessageTemplateForReplace({ field: name, message: errors[0] }));
return true;
}
return false;
}
Maybe this example project will be also helpfull for you. It's assiociated with grid popup editing, but shows mechanism which you want to achieve.

Related

MVC Custom Attribute - Client-side Validation - Warning: No message defined for 'field'

I tried to create a custom data annotation validation attribute (NameValidationAttribute) in MVC 5 project using VS2013. I was able to successfully add the client side validation and the error message for custom validation is getting displayed as soon as the focus leaves the textbox. However, the standard attributes like [Required] and [Range] validators are now not showing proper error messages, says 'Warning: No message defined for 'field' ' (See below screenshot).
Question:
- Why the standard validation error messages are showing as "Warning: No message defined for UnitsInStock"? What am I missing?
Below is my custom client validation script:
I included following scripts in EditProducts page.
Please note that the error messages for UnitPrice, UnitsInStock and ReorderLevel fields are defined with Range validation attribute (see below).
FYI, I tried to change the order of the scripts in ProductEdit page but still its showing the same message.
Please advise!
I ran into this issue. I had created an MVC attribute called PasswordAttribute, with a client side validator called 'password'.
$.validator.addMethod('password', function (value, element, params) {
...[validation logic]
});
$.validator.unobtrusive.adapters.addBool('password');
As soon as I added this logic to the solution I got the error you saw on my Password and ConfirmPassword fields. Note that this occurred before the attribute was even used. Simply renaming the client side validator to 'passwordcheck' fixed the issue. I initially thought that the name 'password' possibly clashed with one of the pre-defined validators (cf. jQuery Validation Documentation) but this doesn't appear to be the case. I suspect now that it is a clash with the name or value for some input field attribute. Anyway, the solution was simply to rename the validator.
jQuery unobtrusive need data-msg for default validate message.
This is how to apply dynamic error message from your model to Html
$.validator.unobtrusive.adapters.add("requireif", function (options) {
$('#' + options.element.id).attr("data-msg", options.message);
// Add rule ...
});
You can change default warning message.
$.validator.addMethod("requireif", function (value, element, pair) {
// validate logic
return true/false;
}, "YOUR DEFAULT MESSAGE HERE");
Or
#Html.TextBoxFor(m => m.Property1, new { Class = "form-control", data_msg = "YOUR DEFAULT MESSAGE HERE" })
Or if you can put it directly to your Html like this.
<input class="form-control" data-msg="YOUR DEFAULT MESSAGE HERE"/>

how to show a response in Razor view

my index view displays the IEnumberable inside an html table. with the links like edit and delete. delete links is create like below.
#* #Html.ActionLink("Delete", "Delete", new { id= SomeId })*#
Inside the controlelr action methods i am calling a service that gives me delete functionality.
CustomResponseObject resp = someService.DeleteSomething(id);
Now this CustomResponseObject has a bool indicating success or failure. and a string mentioned which business rule was negated if any. I want to propagate this message to the Razor in order to show an alert box.
what will be an ideal solution in this case. ?
I would make an ajax call and than display the message depending on the result as you indicated you wanted display the message in an alert box.
$.get("~/Delete", { id: someId }).done(function(data) {
var result = data.IsSuccess ? "success" : "failure";
alert("Your operation was a " + result);
});
Sorry I just noticed you wanted to have it available in Razor. In this case I would add a field to your Model. Than in the Razor view you can access it.
As for displaying it maybe have your JS pick up on the hidden field created using
Html.HiddenFor(m => m.IsSuccess)

Multiple CheckBox Validation using spring JS?

I am creating dynamic Check Boxes in runtime. my requirement is have to validate atleast one checkbox checked or not. am doing this using springJS. But to validate i have to pass checkBox Id to spring Validation, But this ID array creating in runtime. how can i achieve this? i tried all solutions but it did'nt worked for me. i am doing like this it was working if i hardcode checkbox id.
<script type="text/javascript">
Spring.addDecoration(
new Spring.ElementDecoration({
elementId: '_CheckBox_ids',
widgetType: 'dijit.form.CheckBox',
widgetModule: 'dijit.form.CheckBox',
validate: function () {
if (dojo.query("#roo_apiUser_profile > input[type=checkbox]", 'dijit.form').filter(function (n) {
return n.checked;
}).length > 0) {
return true;
} else {
alert('choose at least one profile');
return false;
}
},
widgetAttrs: {
required: true
}
}));
</script>
You may add the onsubmit attribute in your form tag and call a function that does the validation on checkboxes.
Alternately, you may create your own extension of AbstractElementDecoration (defined in spring.js) using dojo.declare and pass to the validate attribute a function that will do the checkboxes validation for you. For elementId you may pass in the id of a div element that contains all the checkboxes. Spring.ValidateAllDecoration calls Spring.validateAll function. Make sure you do the necessary tweaking in your AbstractElementDecoration extension so that there is no exceptions in Spring.validateAll.

How can we show error message on form validation on joomla 2.5 in the same way as email validation with a tooltip like alert?

How can we show error message on form validation on joomla 2.5 in the same way as email validation etc? with the tool tip?
I have included
JHtml::_('behavior.formvalidation');
JHtml::_('behavior.tooltip');
and I have a script
$(document).ready(function () {
var msg = new Array();
document.formvalidator.setHandler('phone', function (value) { return (value != '123'); } );
});
and My input filed is like
<input name="jform[contact_phone]" type="text" id="jform_contact_phone" class='validate-phone'/>
I am getting the tooltip for email field validation and required filed validation, but I can not include numeric validation and I could not implement a tooltip message for my custom phone number field.
I am using joomla 2.5
Please check here for custom validation
http://docs.joomla.org/Client-side_form_validation
You have to add like below:
window.addEvent('domready', function(){
document.formvalidator.setHandler('birth', function(value) {
regex=/^\d{4}-\d{2}-\d{2}$/;
return regex.test(value);
});
});
If its only for numeric click below URL and try this also:
Validate phone number in joomla 2.5

MVC3 Validation, Unobtrusive Validation - Asterisk for validation message

My views have limited space for validation messages and because of this i want to output a asterisk instead of the validation message. The following blog outlines how to do this by adding a extra parameter to the validation helper:
http://www.erroronlineone.com/2011/09/12/mvc3-display-an-asterisk-for-error-message/
#Html.ValidationMessageFor(model => model.Name, "*")
But I want to output a asterisk or an image and using the HTML title attribute have a pop up displaying the validation message. Would I have to change the way unobtrusive validation works? Or do you have a better idea? Thanks
One way, if you are game, is to edit the unobtrusive validation javascript file.
The error message is displayed in the onError function. Here you can change the message element any way you wish. For example (unminified):
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
// Set the "title" attribute and change the text to an asterisk.
error.prop("title", error.text());
error.text("*");
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}

Resources