You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

47 lines
2.1 KiB

import assertString from './util/assertString';
/* eslint-disable max-len */
// from http://goo.gl/0ejHHW
var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; // same as above, except with a strict 'T' separator between date and time
var iso8601StrictSeparator = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
/* eslint-enable max-len */
var isValidDate = function isValidDate(str) {
// str must have passed the ISO8601 check
// this check is meant to catch invalid dates
// like 2009-02-31
// first check for ordinal dates
var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/);
if (ordinalMatch) {
var oYear = Number(ordinalMatch[1]);
var oDay = Number(ordinalMatch[2]); // if is leap year
if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366;
return oDay <= 365;
}
var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number);
var year = match[1];
var month = match[2];
var day = match[3];
var monthString = month ? "0".concat(month).slice(-2) : month;
var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare
var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01'));
if (month && day) {
return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;
}
return true;
};
export default function isISO8601(str) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
assertString(str);
var check = options.strictSeparator ? iso8601StrictSeparator.test(str) : iso8601.test(str);
if (check && options.strict) return isValidDate(str);
return check;
}