I am using VS 2010 with MVC 3 and unobtrusive validation. I am attempting to create a custom range validator to includes warnings where input values are acceptable but unexpected. (I have working functionality to submit the values with wanings by using the ignore option of the form validator)
The unobtrusive component is:
// The adapter to support ASP.NET MVC unobtrusive validation //
$.validator.unobtrusive.adapters.add('rangewithwarning', ['min', 'max', 'wmin', 'wmax', 'warning'],
function (options) {
options.rules['rangewithwarning'] = {
min: options.params.min,
max: options.params.max,
wmin: options.params.wmin,
wmax: options.params.wmax,
warning: options.params.warning
};
options.messages['rangewithwarning'] = options.message;
});
I have Googled extensively on dynamic error messages which seem to come down to three methods but none of these allow me to display the optional error message. These are:
-
Returning the error message
// The validator function $.validator.addMethod('rangewithwarning', function (value, element, params) { if (!value) { return true; // not testing 'is required' here! } var intValue = parseInt(value); // set logic here if (intValue >= params.wmin && intValue <= params.wmax) { // OK within both actual and range warning return true; } if (params.min <= intValue && intValue <= params.max) { // outside warning but within allowed range - show warning return params.warning; } return $.validator.messages.rangewithwarning;});
-
Use showErrors
// The validator function $.validator.addMethod('rangewithwarning', function (value, element, params) { if (!value) { return true; // not testing 'is required' here! } var validator = this; var intValue = parseInt(value); // set logic here if (intValue >= params.wmin && intValue <= params.wmax) { // OK within both actual and range warning return true; } if (params.min <= intValue && intValue <= params.max) { // outside warning but within allowed range - show warning var errors = new Object(); errors[element.name] = params.warning; validator.showErrors(errors); } return false; }); -
Return an additional parameter from a
messagerfunction
None of these worked although when stepping through the second one the optional message was shown briefly then overwritten.
I’m clearly missing something obvious but cannot see what it is.
Thanks in advance.
Found a solution which was to use the standard range attribute and then follow it with my new warn only attribute
Where the class
warningOnlyDataOKis used to both display a different style error message and to ignore that validation on save.