2011-07-28 69 views
6

我發現這個有用的代碼允許英國日期在Chrome中工作,但我不知道如何實現它。它覆蓋默認的日期功能。覆蓋jQuery的日期

date: function(value, element) { 
    //ES - Chrome does not use the locale when new Date objects instantiated: 
    //return this.optional(element) || !/Invalid|NaN/.test(new Date(value)); 
    var d = new Date(); 
    return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value))); 
}, 

我如何將此添加到jQuery驗證以覆蓋默認功能。

Here is where我找到了代碼示例

+0

我會建議使用類似的東西:http://www.datejs.com/ – Mrchief

+0

如果你打算複製另一個問題的答案,至少給這個人的功勞。 (你甚至複製了他們的拼寫錯誤)http://stackoverflow.com/questions/5966244/jquery-datepicker-chrome –

回答

16

您應該加載jquery.validate庫,像這樣後調用validator.addMethod方法:

$(function() { 
    // Replace the builtin US date validation with UK date validation 
    $.validator.addMethod(
     "date", 
     function (value, element) { 
      var bits = value.match(/([0-9]+)/gi), str; 
      if (!bits) 
       return this.optional(element) || false; 
      str = bits[1] + '/' + bits[0] + '/' + bits[2]; 
      return this.optional(element) || !/Invalid|NaN/.test(new Date(str)); 
     }, 
     "Please enter a date in the format dd/mm/yyyy" 
    ); 
}); 

請注意,我用的實際驗證輸入的另一種方式,因爲你的問題中的代碼不會工作(toLocaleDateString不帶參數)。正如Mrchief在評論中指出的那樣,您也可以將其更改爲使用datejs庫。

+1

這是最優雅的解決方案,謝謝。 – Emanuel