Reputation: 559
I have a page with ZipCode field, which I need to validate on server. When the page is loaded ZipCode must be already prefilled from some external source.
I added a jquery remote validator in order to validate this field: $(document).ready(function () {
$("#Buyer_ZipCode").rules("add", {
remote: { url: zipcodeValidationUrl, async: false },
messages:
{
remote: "Cannot determine location for given zip code."
}
});
var zipcode = $("#Buyer_ZipCode");
if (zipcode.val().length > 0) {
zipcode.trigger('blur');
};
});
In order to do the actions at once after the page load I added a blur trigger. My Blur handler:
$("#Buyer_ZipCode").bind('blur', function (e) {
//some actions
element = $(e.target);
if (!element.valid()) {
console.log(element.val());
// Invalidate lookup target control.
targetCity.get(0).value = "";
targetState.get(0).value = "";
return;
};
// yet some actions
});
Everything works normally, except the situation when the page is loaded and we already have a value for ZipCode field. In this case valid() method always returns false, nevertheless remote validion is not async and the server really returns true. By the way, this is my validation controller
public JsonResult IsZipCodeValid([NestedFieldModelBinder]string Buyer_ZipCode)
{
if (Utils.GetZipcode(Buyer_ZipCode) != null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("Cannot determine location for given zip code.", JsonRequestBehavior.AllowGet);
}
What am I doing wrong?
Upvotes: 1
Views: 493
Reputation: 13381
You'll find it much simpler and cleaner to use the RemoteAttribute .
In your viewmodel add a Remote[] attribute to your Buyer_ZipCode property
[Remote("ValidateZipCode", HttpMethod="Post", ErrorMessage = "Cannot determine location for given zip code.")]
public string Buyer_ZipCode{ get; set; }
And your action for validation:
[HttpPost]
public ActionResult ValidateZipCode(string Buyer_ZipCode)
{
// do your validation
return Json(true);
}
Regards
Upvotes: 1