Dean Friedland Dean Friedland - 4 years ago 86
Javascript Question

Knockout custom validation ajax issue

I am trying to validate whether or not a zip code entered into a form field is valid for a state chosen from a dropdown in the preceeding field. I have all the data in a table and am able to confirm using an ajax call. My code below allows me to make the ajax call an return true/false, but I am not sure how to trigger the validation based off the return value. Does anyone have an idea?

Custom Validation:

ko.validation.rules["isValidZipCode"] =
{
getValue: function (o) {
return (typeof o === 'function' ? o() : o);
},
validator: function (val, fields) {
var self = this;
var anyOne = ko.utils.arrayFirst(fields, function (field) {
var val = self.getValue(field);

if (val === undefined || val === null)
return "";
return true;
});

var ajaxData = { state: anyOne, zipCode: val }
$.ajax({
url: $("a#ValidateZipByState").attr("href"),
type: "POST",
data: ajaxData,
success: function (isValid) {
if (isValid) {
return true;
} else {
return false;
}
},
error: handleSubmitError
});

return;
},
message: "Invalid zip code for this state"
};


ViewModel:

self.State = ko.observable(model.State).extend({ required: true });
self.ZipCode = ko.observable(model.ZipCode).extend({ required: true, pattern: /^[0-9]{5}(?:-[0-9]{4})?$/g, isValidZipCode: [self.State, self.ZipCode] });

Answer Source

It looks like you need to set the async flag on your validation definition, and then you can return a result to the callback parameter. Reference

ko.validation.rules["isValidZipCode"] =
{
    async: true,
    getValue: function (o) {
        return (typeof o === 'function' ? o() : o);
    },
    validator: function (val, fields, callback) {
        var self = this;
        var anyOne = ko.utils.arrayFirst(fields, function (field) {
            var val = self.getValue(field);

            if (val === undefined || val === null) 
                return "";                
            return true;
        });

        var ajaxData = { state: anyOne, zipCode: val }
        $.ajax({
            url: $("a#ValidateZipByState").attr("href"),
            type: "POST",
            data: ajaxData,
            success: function (isValid) {
                callback(isValid);
            },
            error: handleSubmitError
        });

        return;
    },
    message: "Invalid zip code for this state"
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download