如何使用 jquery 验证这种格式 (yyyy-mm-dd) 的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18758772/
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
How do I validate a date in this format (yyyy-mm-dd) using jquery?
提问by user2648752
I am attempting to validate a date in this format: (yyyy-mm-dd). I found this solution but it is in the wrong format for what I need, as in: (mm/dd/yyyy).
我正在尝试以这种格式验证日期:(yyyy-mm-dd)。我找到了这个解决方案,但它的格式不符合我的需要,如:(mm/dd/yyyy)。
Here is the link to that solution: http://jsfiddle.net/ravi1989/EywSP/848/
这是该解决方案的链接:http: //jsfiddle.net/ravi1989/EywSP/848/
My code is below:
我的代码如下:
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for mm/dd/yyyy format.
dtMonth = dtArray[1];
dtDay= dtArray[3];
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;
}
What regex pattern can I use for this that will account for invalid dates and leap years?
我可以为此使用什么正则表达式模式来解释无效日期和闰年?
回答by Goblinlord
I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function.
我稍微扩展了上面发布的 isValidDate 函数 Thorbin(使用正则表达式)。我们使用正则表达式来检查格式(以防止我们获得对日期有效的另一种格式)。在这个松散的检查之后,我们实际上通过 Date 构造函数运行它,如果它在此格式中有效,则返回 true 或 false。如果它不是一个有效的日期,我们将从这个函数中得到错误。
function isValidDate(dateString) {
var regEx = /^\d{4}-\d{2}-\d{2}$/;
if(!dateString.match(regEx)) return false; // Invalid format
var d = new Date(dateString);
var dNum = d.getTime();
if(!dNum && dNum !== 0) return false; // NaN value, Invalid date
return d.toISOString().slice(0,10) === dateString;
}
/* Example Uses */
console.log(isValidDate("0000-00-00")); // false
console.log(isValidDate("2015-01-40")); // false
console.log(isValidDate("2016-11-25")); // true
console.log(isValidDate("1970-01-01")); // true = epoch
console.log(isValidDate("2016-02-29")); // true = leap day
console.log(isValidDate("2013-02-29")); // false = not leap day
回答by Thorben Croisé
You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).
如果这对您来说足够了,您也可以使用正则表达式来完成稍微简单的工作(例如,如 [1] 中所见)。
They are build in into javascript so you can use them without any libraries.
它们内置于 javascript 中,因此您可以在没有任何库的情况下使用它们。
function isValidDate(dateString) {
var regEx = /^\d{4}-\d{2}-\d{2}$/;
return dateString.match(regEx) != null;
}
would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].
将是一个函数来检查给定的字符串是否是四个数字 - 两个数字 - 两个数字(几乎是 yyyy-mm-dd)。但是您可以使用更复杂的表达式做更多的事情,例如检查 [2]。
isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true
回答by Frederik.L
Since jQuery is tagged, here's an easy / user-friendly way to validate a field that must be a date (you will need the jQuery validation plugin):
由于 jQuery 被标记,这里有一种简单/用户友好的方法来验证必须是日期的字段(您将需要jQuery 验证插件):
html
html
<form id="frm">
<input id="date_creation" name="date_creation" type="text" />
</form>
jQuery
jQuery
$('#frm').validate({
rules: {
date_creation: {
required: true,
date: true
}
}
});
UPDATE:After some digging, I found no evidence of a ready-to-go parameter to set a specific date format.
更新:经过一番挖掘,我没有发现任何可以设置特定日期格式的现成参数的证据。
However, you can plug in the regex of your choice in a custom rule :)
但是,您可以在自定义规则中插入您选择的正则表达式 :)
$.validator.addMethod(
"myDateFormat",
function(value, element) {
// yyyy-mm-dd
var re = /^\d{4}-\d{1,2}-\d{1,2}$/;
// valid if optional and empty OR if it passes the regex test
return (this.optional(element) && value=="") || re.test(value);
}
);
$('#frm').validate({
rules: {
date_creation: {
// not optional
required: true,
// valid date
date: true
}
}
});
This new rule would imply an update on your markup:
这条新规则意味着对您的标记进行更新:
<input id="date_creation" name="date_creation" type="text" class="myDateFormat" />
回答by Zaheer Ahmed
try this Here is working Demo:
试试这个这是工作演示:
$(function() {
$('#btnSubmit').bind('click', function(){
var txtVal = $('#txtDate').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
});
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for mm/dd/yyyy format.
dtMonth = dtArray[3];
dtDay= dtArray[5];
dtYear = dtArray[1];
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;
}
});
changed regex is:
改变的正则表达式是:
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
回答by Koko
Here's the JavaScript rejex for YYYY-MM-DD format
这是 YYYY-MM-DD 格式的 JavaScript rejex
/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
回答by Pascal
I recommend to use the Using jquery validation plugin and jquery ui date picker
我建议使用 Using jquery validation plugin 和 jquery ui date picker
jQuery.validator.addMethod("customDateValidator", function(value, element) {
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}
},
"Please enter a valid date format dd-mm-yyyy"
);
this.ui.form.validate({
debug: true,
rules : {
title : { required : true, minlength: 4 },
date : { required: true, customDateValidator: true }
}
}) ;
Using Jquery and date picker just create a function with
使用 Jquery 和日期选择器只需创建一个函数
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}
You might use only the regular expression for validation
您可能只使用正则表达式进行验证
// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ;
return re.test(value)
Of course the date format should be of your region
当然日期格式应该是你所在的地区
回答by Pascal
Just use Date
constructor to compare with string input:
只需使用Date
构造函数与字符串输入进行比较:
function isDate(str) {
return 'string' === typeof str && (dt = new Date(str)) && !isNaN(dt) && str === dt.toISOString().substr(0, 10);
}
console.log(isDate("2018-08-09"));
console.log(isDate("2008-23-03"));
console.log(isDate("0000-00-00"));
console.log(isDate("2002-02-29"));
console.log(isDate("2004-02-29"));
Edited:Responding to one of the comments
编辑:回应其中一条评论
Hi, it does not work on IE8 do you have a solution for – Mehdi Jalal
嗨,它在 IE8 上不起作用你有解决方案吗 – Mehdi Jalal
function pad(n) {
return (10 > n ? ('0' + n) : (n));
}
function isDate(str) {
if ('string' !== typeof str || !/\d{4}\-\d{2}\-\d{2}/.test(str)) {
return false;
}
var dt = new Date(str.replace(/\-/g, '/'));
return dt && !isNaN(dt) && 0 === str.localeCompare([dt.getFullYear(), pad(1 + dt.getMonth()), pad(dt.getDate())].join('-'));
}
console.log(isDate("2018-08-09"));
console.log(isDate("2008-23-03"));
console.log(isDate("0000-00-00"));
console.log(isDate("2002-02-29"));
console.log(isDate("2004-02-29"));
回答by Niet the Dark Absol
Rearrange the regex to:
将正则表达式重新排列为:
/^(\d{4})([\/-])(\d{1,2})(\d{1,2})$/
I have done a little more than just rearrange the terms, I've also made it so that it won't accept "broken" dates like yyyy-mm/dd
.
我所做的不仅仅是重新排列条款,我还做了它,以便它不会接受像yyyy-mm/dd
.
After that, you need to adjust your dtMonth
etc. variables like so:
之后,您需要dtMonth
像这样调整您的等变量:
dtYear = dtArray[1];
dtMonth = dtArray[3];
dtDay = dtArray[4];
After that, the code should work just fine.
之后,代码应该可以正常工作。
回答by Vinay Pratap Singh
回答by Yoav Schniederman
moment(dateString, 'YYYY-MM-DD', true).isValid() ||
moment(dateString, 'YYYY-M-DD', true).isValid() ||
moment(dateString, 'YYYY-MM-D', true).isValid();