I’m fairly new at creating custom unobtrusive validation, and am running into a weird problem.
This validation basically just checks the database (via Ajax) to see if the model and serial number combination already exists. The jQuery and Ajax seem to be behaving as expected, but my validation message appears as soon as my validation function is called.
Here is my jQuery:
$.validator.addMethod('newserialandmodel',
function (value, element, parameters) {
var modelNumber = $('#ProductInformation_ModelNumber').val();
var serialNumber = value;
var token = $('input[name=__RequestVerificationToken]').val();
$.ajax({
type: "POST",
url: "/ajax/getmodelandserialexists/",
data: ({
modelNumber: modelNumber,
serialNumber: serialNumber,
'__RequestVerificationToken': token
}),
cache: true,
dataType: 'json',
success: function (response) {
if (response.exists) {
$.validator.messages.newserialandmodel =
$.format($.validator.messages.newserialandmodel);
}
return !response.exists;
}
});
return false;
}
);
$.validator.unobtrusive.adapters.add(
'newserialandmodel',
function (options) {
options.rules['newserialandmodel'] = options.params;
if (options.message != null) {
$.validator.messages.newserialandmodel = options.message;
}
}
);
Here is what the form element looks like:
<input type="text" value=""
name="ProductInformation.SerialNumber" id="ProductInformation_SerialNumber"
data-val-required="The Serial number field is required."
data-val-newserialandmodel="There is already a contract with the provided model and serial numbers."
data-val-length-max="30"
data-val-length="The 30 field requires no more than 30 characters."
data-val="true" class="input-validation-error">
When I step through, as soon as it hits the first line of the validation, the message is already shown:
There is already a contract with the provided model and serial numbers.
Also, even though the function returns true, it the message remains.
The rest of the function/Ajax works just fine, I just can figure out why it’s showing this message immediately, and why it stays there when I return true.
Any idea what’s going on?
Thanks to Greg and Zero’s responses, it led me to playing around w/ the return value a bit more.
The problem is that the
returnwithin my Ajax success function just returns the response back to the success function, not the validation function. So I had to change it to set a value within the Ajax success function, and return that.It’s also worth noting that I had to include
async: false, as otherwise the validation function will return (the default value offalse) before the Ajax call completes.