1
votes

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?

3

3 Answers

1
votes

I think it's because you are returning false at the end of your function. So the function will return false, and then the success callback fires trying to return true but it's too late and false has already been returned to the validator. A simple solution would be to make your AJAX call synchronously using async: false.

1
votes

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 return within 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 of false) before the Ajax call completes.

$.validator.addMethod('newserialandmodel',
    function (value, element, parameters) {
        var modelNumber = $('#ProductInformation_ModelNumber').val();
        var serialNumber = value;

        var token = $('input[name=__RequestVerificationToken]').val();

        var isValid = false;

        $.ajax({
            type: "POST",
            url: "/ajax/getmodelandserialexists/",
            data: ({ 
                    modelNumber: modelNumber, 
                    serialNumber: serialNumber, 
                    '__RequestVerificationToken': token }),
            async: false,
            dataType: 'json',
            success: function (response) {
                if (response.exists) {
                    $.validator.messages.newserialandmodel = 
                        $.format($.validator.messages.newserialandmodel);
                }

                isValid = !response.exists;
            }
        });

        return isValid;
    }
);
0
votes

A couple of guesses:

  1. You have "cache: true", which means that it will not fetch from the server if the URL is the same. I don't know if caching checks POSTed parameters, so it's possible that even with different parameters it will use the cached version. Try setting cache to false.

  2. I'm not familiar with the adapters API, but is it possible that previous activity has caused the condition to be met? (the options are not in fact null when this is being executed)?