admin管理员组文章数量:1135944
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).
Here is the link to that solution: /
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?
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).
Here is the link to that solution: 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?
Share Improve this question edited Feb 15, 2016 at 17:00 user57508 asked Sep 12, 2013 at 8:05 user2648752user2648752 2,2215 gold badges23 silver badges29 bronze badges 1- same issue with me , there is a problem in leap year dates. any solution ? – Viral Patel Commented Nov 24, 2020 at 9:48
11 Answers
Reset to default 135I 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.
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
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]).
They are build in into javascript so you can use them without any libraries.
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].
isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true
- [1] Javascript - Regex to validate date format
- [2] http://www.regular-expressions.info/dates.html
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):
html
<form id="frm">
<input id="date_creation" name="date_creation" type="text" />
</form>
jQuery
$('#frm').validate({
rules: {
date_creation: {
required: true,
date: true
}
}
});
DEMO + Example
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" />
Here's the JavaScript rejex for YYYY-MM-DD format
/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
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
moment(dateString, 'YYYY-MM-DD', true).isValid() ||
moment(dateString, 'YYYY-M-DD', true).isValid() ||
moment(dateString, 'YYYY-MM-D', true).isValid();
I recommend to use the Using jquery validation plugin and 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
// 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
Just use Date
constructor to compare with string input:
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
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"));
Rearrange the regex to:
/^(\d{4})([\/-])(\d{1,2})\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
.
After that, you need to adjust your dtMonth
etc. variables like so:
dtYear = dtArray[1];
dtMonth = dtArray[3];
dtDay = dtArray[4];
After that, the code should work just fine.
Working Demo fiddle here Demo
Changed your validation function to this
function isDate(txtDate)
{
return txtDate.match(/^d\d?\/\d\d?\/\d\d\d\d$/);
}
You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE
if everythings check out to be correct or FALSE
if anything is invalid. It doesn't get easier then this!
function validateDate(date) {
var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[3];
var m = matches[2] - 1;
var y = matches[1] ;
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
Be aware that months need to be subtracted like this: var m = matches[2] - 1;
else the new Date()
instance won't be properly made.
本文标签: javascriptHow do I validate a date in this format (yyyymmdd) using jqueryStack Overflow
版权声明:本文标题:javascript - How do I validate a date in this format (yyyy-mm-dd) using jquery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736907552a1956033.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论