0

I'm having a problem with this code that I can't seem to figure out:

$.validator.addMethod('street_address', function (value, element) {
  var address  = value + ', ' + $(element).parent().parent().find("#venue_city_id option:selected").text(),
      geocoder = new google.maps.Geocoder(),
      that     = this;
  geocoder.geocode({address: address}, function (results, status) {
    return that.optional(element) || status == google.maps.GeocoderStatus.OK;
  });
}, 'invalid address');

It works to invalidate an incorrect address (one that is not geocodeable by Google). The problem is even when it returns true, I'm still getting 'invalid address'. Any ideas on what the problem might be?

1 Answer 1

1

You return from inside callback in

geocoder.geocode({address: address}, function (results, status) {
    return that.optional(element) || status == google.maps.GeocoderStatus.OK;
});

Not from validator function.

Moreover, geocoder.geocode performs, I believe, asynchronous ajax query, so you'll not be able to tell whether your location is "geocodeable" when leaving you validator. There should be a specific validator for such cases in jQuery validation, called remote or something, which validates basing on the result of ajax query.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, it seems it has to do with the fact that geocoder.geocode is an async request. The remote validation doesn't seem to be what I need, though.
The reason for why the code does not work is 100% clear, not just "seems": you do not return from the validator function. You define another function inline and return from it, but it has influence on how the validator works. The fix is not easy, as geocoder.geocode is async, but the fix was not a question.
it has NO influence I meant to say

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.