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

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"/>

Related

model is not defined in ajax call response in mvc

I am sending model and checkbox value data to the controller from the view. While at run time it showing me error i.e. model is not defined. This error is showing me when I call the ajax in mvc view.
Here is my code,
#model VendorModel
<input type="checkbox" id="chb_wholesale" onclick="WholeSaleCheck()" />#T("WholeSale")
<script>
function WholeSaleCheck() {
alert(Model.vendorId);
}
</script>
Now, I am surprised that why showing me this type of error because Model also available and after tying the Model word showing list of their property field also one of the field is vendorId and that also automatically**(by pressing ctrl+space)**.
Got the solution, by coding this #Model.vendorId error is solve out.

parsley.js prevents submit after failing ajax validation has been corrected

i have a form where i need to see if an email address entered into the form is already in a database. this check needs to be performed conditionally based on the value of another field in the form.
here is the form field:
<input type="email" value="" class="form-control" name="email_bill" id="email" required data-parsley-type="email" data-parsley-registered="1" data-parsley-trigger="focusout submit">
and here's the validator code:
Parsley.addValidator('registered', {
validateString: function(value) {
if ($('input[name="d_type"]:checked').val() == 'S') {
return $.ajax({
type: "POST",
url: "/is_registered.html",
data: $('form').serialize()
});
} else {
var parent = $('#email').closest('div');
var this_id = $('#email').attr('data-parsley-id');
$(parent).removeClass('has-error').addClass('parsley-success');
$(this_id).remove();
return true;
}
},
messages: {en: "Someone has already registered with the Email address you entered"}
});
the server code is trivial and returns a '200 OK' header if the address isn't in the database and a '404 Not Found' if it is. that works.
i followed the example in the parsley.js custom validator example for the simple ajax request.
what happens is: if i enter a 'registered' address, i get the appropriate error message. if i then go and modify that address to one i know is NOT registered and tab or mouse out to the next field, the error message goes away, BUT the submit button doesn't work. to further complicate the situation, if i load and fill out a form with a 'non-registered' address, the submit button doesn't work either. it appears that execution of the custom validator disables submit upon entry.
i've played with this for hours, trying all sorts of event manipulation, but nothing works.
i should point out that if the checked value of d_type (see field definition above) is NOT 'S', then everything works as expected.
i am totally baffled as to why following the documentation results in failure.
as it turns out, this was not a problem with parsley at all.
a colleague created the form and the submit button had an id of "submit' which could not allow parsley to resolve the submit handler. under those circumstances, apparently parsley blocks the submit.
who knew?
well now, we know.....

Knockout js + Laravel localization

Knockout JS includes some build-in validation messages such as
"This field is required"
"Please enter at least {0} characters."
and so on.
How can I translate these messages ? If I just replace them with "#lang(..) or "trans(..)" it does not works..
Laravel does not have build in functions for translations.
If you want to use messages in other languages you will have to add them to the language files.
Here is how I overrided and translated the knockout validation messages:
var = ko.observable().extend({required: {
params: true,
message: "#lang('errors.required_field')"
}})

Symfony 2 custom validator on field

I made my custom date range validator, and I'm using it on date properties of my entity..
Though, when I get an error it's attached to the form and not to the field.
So I can't display errors with {{form_errors(form.date)}}. (edit : form is a prototype of a child collection)
I saw that : Custom constraint validation error doesn't display next to field in Symfony2 . But I don't want to explicitly specify on which field name the error should be attached..
Maybe it's related to the fact that this error is in a collection of the main form (using his prototype) ?
I could also add that the error is attached to the main parent form (my validator is on a field, which is in a form, which is a collection of a form, which is an embedded form of the main form).
How can I do ?
EDIT : It might be related to that : https://stackoverflow.com/questions/15907415/symfony2-data-prototype-error-bubbling
It is surely related to error_bubbling. It defaults to true if the form is compound, so you should set it to false value.
$builder
->add('field', 'collection', [
'type' => new ChildFormType(),
'error_bubbling' => false,
]);
See symfony doc page about error_bubbling for more details

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