MVC3 Validation, Unobtrusive Validation - Asterisk for validation message - asp.net-mvc-3

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();
}
}

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)

Kendo UI: Displaying server-side errors using Kendo Validator

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.

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

codeigniter: Return form validator results as string

I'm new to codeigniter so sorry for the simple question.
I want to run formvalidator for my ajax process. How can I return the valdiation errors as JSON? Is there a better way to do this?
Thanks
you haven't really stated what you are doing. i am going to assume that you have a form that you want to save data in, using ajax, so that you don't have any of those pesky save/submit buttons. also, i am guessing that you have some sort of .change() handler that sends the form element to the ajax handler as a post variable as a name/value pair.
the problem you will run into, is that when you run the form validator on your data it will always fail. because the form validator needs all of the fields for that form, and you will only send one piece of data at a time.
normally in the code igniter example code you check to see if the 'run' method passess or not. in your case it doesn't really matter because it will always fail, so don't bother checking. here is a snippet of some example code
$this->form_validation->run('form'); // it is likely that the form won't validate, but thats ok.
$validation_error=form_error($field_name);
if($validation_error){
$feedback = 'Field <strong>NOT</strong> saved.';
}else{
// no errors, we can save.
$this->my_model->set_field($id,$field_name,$field_value);
$validation_error=' '; // this is set so if the field was initially not validated, and it is later, the validation message goes away.
$validation_element = '#'.$field_name;
$feedback = 'Field saved.';
}
....
echo json_encode(array('feedback'=>$feedback,'validation_element'=>'#'.$field_name,'validation_error'=>$validation_error));
break;
in my snippet, a json object is returned to the ajax post. in the jquery ajax post,the success handler has this snippet of code.
try{
var json = $.parseJSON(data);
if(typeof(json.container)==='string'){
var container=json.container;
}
if(typeof(json.html)==='string'){
var con = $(container);
$(con).html(json.html);
}
if(typeof(json.feedback)==='string'){
display_feedback(json.feedback);}
if(typeof(json.validation_element) ==='string'){
// assumes that if a validation_element object is returned, it has a paired validation_error element.
$(json.validation_element).closest('.col_b').nextAll('.validation_error').first().html(json.validation_error);
}
}
catch(err){
display_feedback(err);
}
in my form, i have a three column format, where:
<div class='col_a'>label</div>
<div class='col_b' >input, id = field_name </div>
<div class='col_c validation_error'>validation text</div>
hopefully that makes some sense to you.

Resources