2011-08-08 41 views
0

我有這個代碼的問題,我似乎無法弄清楚:問題與定製jQuery.validator規則

$.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'); 

它的工作原理無效的地址不正確(一個由不geocodeable谷歌)。問題是即使它返回true,我仍然收到'無效地址'。任何想法可能是什麼問題?

回答

1

您從內回調

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

返回Not從驗證功能。

此外,geocoder.geocode執行,我相信,異步ajax查詢,所以當你離開你驗證器時,你將無法判斷你的位置是否是「geocodeable」。在jQuery驗證中應該有一個特定的驗證器,稱爲remote或其他,它根據ajax查詢的結果進行驗證。

+0

是的,它似乎與'geocoder.geocode'是一個異步請求有關。雖然遠程驗證似乎不是我所需要的。 –

+0

爲什麼代碼無法正常工作的原因是100%清除,而不僅僅是「看起來」:您不會從驗證器功能返回。你定義了另一個內聯函數並從中返回,但它對驗證器的工作方式有影響。修復並不容易,因爲'geocoder.geocode'是異步的,但修復不是問題。 –

+0

它沒有影響,我打算說 –