jQuery 带有 jQuery 验证插件的自定义日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/511439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom date format with jQuery validation plugin
提问by Bruno
How can I specify a custom date formate to be validated with the Validation Pluginfor jQuery?
如何指定要使用jQuery验证插件进行验证的自定义日期格式?
回答by nickf
You can create your own custom validation method using the addMethod
function. Say you wanted to validate "dd/mm/yyyy":
您可以使用该addMethod
函数创建自己的自定义验证方法。假设您想验证“dd/mm/yyyy”:
$.validator.addMethod(
"australianDate",
function(value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy."
);
And then on your form add:
然后在您的表单上添加:
$('#myForm')
.validate({
rules : {
myDate : {
australianDate : true
}
}
})
;
回答by Craig Stuntz
nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.
nickf 的回答很好,但请注意,验证插件已经在 additional-methods.js 文件中包含了其他几种日期格式的验证器。在你自己写之前,确保有人还没有写过。
回答by Soth
I personally use the very good http://www.datejs.com/library.
我个人使用非常好的http://www.datejs.com/库。
Docco here: http://code.google.com/p/datejs/wiki/APIDocumentation
Docco 在这里:http: //code.google.com/p/datejs/wiki/APIDocumentation
You can use the following to get your Australian format and will validate the leap day 29/02/2012 and not 29/02/2011:
您可以使用以下内容获取澳大利亚格式,并将验证闰日 29/02/2012 而不是 29/02/2011:
jQuery.validator.addMethod("australianDate", function(value, element) {
return Date.parseExact(value, "d/M/yyyy");
});
$("#myForm").validate({
rules : {
birth_date : { australianDate : true }
}
});
I also use the masked input plugin to standardise the data http://digitalbush.com/projects/masked-input-plugin/
我还使用了屏蔽输入插件来标准化数据http://digitalbush.com/projects/masked-input-plugin/
$("#birth_date").mask("99/99/9999");
回答by Babailiica
Here is an example for a new validation method that will validate almost any date format, including:
下面是一个新的验证方法的例子,它可以验证几乎所有的日期格式,包括:
- dd/mm/yy or dd/mm/yyyy
- dd.mm.yy or dd.mm.yyyy
- dd,mm,yy or dd,mm,yyyy
- dd mm yy or dd mm yyyy
- dd-mm-yy or dd-mm-yyyy
- dd/mm/yy 或 dd/mm/yyyy
- dd.mm.yy 或 dd.mm.yyyy
- dd,mm,yy 或 dd,mm,yyyy
- dd mm yy 或 dd mm yyyy
- dd-mm-yy 或 dd-mm-yyyy
Then, when you pass the value to the php you can convert it with strtotime
然后,当您将值传递给 php 时,您可以使用strtotime将其转换
Here is how to add the method:
添加方法的方法如下:
$.validator.addMethod("anyDate",
function(value, element) {
return value.match(/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2])[/., -](19|20)?\d{2}$/);
},
"Please enter a date in the format!"
);
Then you add the new filter with:
然后你添加新的过滤器:
$('#myForm')
.validate({
rules : {
field: {
anyDate: true
}
}
})
;
;
回答by Simon Wheatley
Here's a specific code sample which worked for me recently:
这是最近对我有用的特定代码示例:
// 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"
);
I should note that this actually replaces the built-in date validation routine, though I couldn't see that this should cause an issue with the current plugin.
我应该注意到这实际上取代了内置的日期验证例程,尽管我看不出这会导致当前插件出现问题。
I then applied this to the form using:
然后我使用以下方法将其应用于表单:
$( '#my_form input.date' ).rules( 'add', { date: true } );
回答by Kwex
This is me combining/modifying previous posts to achieve my desired result:
这是我结合/修改以前的帖子以达到我想要的结果:
// Override built-in date validator
$.validator.addMethod(
"date",
function (value, element) {
//Return NB: isRequired is not checked at this stage
return (value=="")? true : isDate(value);
},
"* invalid"
);
Add Date validation after your validation config. I.e. after calling the $(form).validate({ ... }) method.
在验证配置后添加日期验证。即在调用 $(form).validate({ ... }) 方法之后。
//Add date validation (if applicable)
$('.date', $(frmPanelBtnId)).each(function () {
$(this).rules('add', {
date: true
});
});
Finally, the main isDate Javascript function modified for UK Date Format
最后,主要的isDate Javascript函数修改为UK Date Format
//Validates a date input -- http://jquerybyexample.blogspot.com/2011/12/validate-date- using-jquery.html
function isDate(txtDate) {
var currVal = txtDate;
if (currVal == '')
return false;
//Declare Regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for dd/mm/yyyy format.
var dtDay = dtArray[1];
var dtMonth = dtArray[3];
var dtYear = dtArray[5];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay > 31)
return false;
else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
return false;
else if (dtMonth == 2) {
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay > 29 || (dtDay == 29 && !isleap))
return false;
}
return true;
}
回答by Chris Love
Jon, you have some syntax errors, see below, this worked for me.
乔恩,你有一些语法错误,见下文,这对我有用。
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod(
"australianDate",
function (value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy"
);
$('#testForm').validate({
rules: {
"myDate": {
australianDate: true
}
}
});
});
回答by mingyu
$.validator.addMethod("mydate", function (value, element) {
return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);
});
you can input like yyyy-mm-dd
also yyyy/mm/dd
你可以像输入yyyy-mm-dd
也yyyy/mm/dd
but can't judge the the size of the month sometime Feb just 28 or 29 days.
但无法判断 2 月 28 天或 29 天的月份大小。
回答by Ricky
Check out: jQuery Masked Input Plugin
查看: jQuery 屏蔽输入插件
回答by Rijo
@blasteralfred:
@blasteralfred:
I got following rule validating correct date for me (DD MM YYYY)
我得到了以下规则来验证我的正确日期(DD MM YYYY)
jQuery.validator.addMethod(
"validDate",
function(value, element) {
return value.match(/(?:0[1-9]|[12][0-9]|3[01]) (?:0[1-9]|1[0-2]) (?:19|20\d{2})/);
},
"Please enter a valid date in the format DD MM YYYY"
);
);
For DD/MM/YYYY
对于 DD/MM/YYYY
jQuery.validator.addMethod(
"validDate",
function(value, element) {
return value.match(/(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/);
},
"Please enter a valid date in the format DD/MM/YYYY"
);
);
This will not validate 01 13 2017 and 01/13/2017.
这不会验证 01 13 2017 和 01/13/2017。
And also does not validate 50 12 2017 and 50/12/2017.
并且也不验证 50 12 2017 和 50/12/2017。