覆盖jquery日期 [英] Override jquery date
问题描述
我发现这个有用的一段代码允许uk日期在Chrome中工作,但我不知道如何实现它。它覆盖默认日期功能。
date:function(value,element){
// ES - Chrome does新的Date对象实例化时不使用locale:
// 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验证以覆盖默认功能。 / p>
你应该调用validator.addMethod方法在加载jquery.validate库后,如下所示:
$(function(){
//替换内置美国日期验证与英国日期验证
$ .validator.addMethod(
date,
function(value,element){
var bits = value.match(/([ 0-9] +)/ gi),str;
if(!bits)
return this.optional(element)|| false;
str = bits [1] +'/' + bit [0] +'/'+ bits [2];
return this.optional(element)||!/ Invalid | NaN / .test(new Date(str));
}
请输入日期格式为dd / mm / yyyy
);
});
请注意,我使用了另一种实际验证输入的方式,因为您的问题中的代码将无法正常工作(toLocaleDateString不带参数)。您也可以在评论中指出,Mrchief指出,您也可以使用datejs库。
I've found this useful bit of code that allows uk dates to work in Chrome but I'm not sure how to implement it. It overrides the default date functionality.
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)));
},
How can I add this into jQuery validate to override the default functionality.
Here is where I found the code sample
You should call the validator.addMethod method after loading the jquery.validate library like so:
$(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"
);
});
Note that I used another way of actually validating the input, as the code in your question will not work (toLocaleDateString doesn't take a parameter). You could also change this to use the datejs library as Mrchief pointed out in the comments.
这篇关于覆盖jquery日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!