I have created a custom validation function that checks whether a zip code entered in a form field is valid for the selected state from a dropdown. The validation works correctly when I initially select a state and then input a zip code, but if I change the state after validation, the error message does not reappear. Can someone help me understand why it's not re-validating?
Custom Validation:
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) {
if (isValid) {
callBack(true);
} else {
callBack(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] });