Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix isDate() handling of ISO8601 timezones #444

Merged
merged 3 commits into from
Oct 20, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#### HEAD

- Fix `isDate()` handling of ISO8601 timezones
([#444](https://github.com/chriso/validator.js/pull/444))
- Fix the incorrect `isFloat('.') === true`
([#443](https://github.com/chriso/validator.js/pull/443))
- Added a Norwegian locale to `isMobilePhone()`
Expand Down
5 changes: 5 additions & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -889,6 +889,11 @@ describe('Validators', function () {
, '2009-05-19 14:39:22-06:00'
, '2009-05-19 14:39:22+0600'
, '2009-05-19 14:39:22-01'
, '2015-10-20T00:53:09+08:00'
, '2015-10-20T00:53:09+09:00'
, '2015-10-20T00:53:09+10:00'
, '2015-10-20T00:53:09+11:00'
, '2015-10-20T00:53:09+12:00'
, '2007-04-06T00:00'
, '2010-02-18T16:23:48.5'
, '200905'
Expand Down
29 changes: 28 additions & 1 deletion validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -470,10 +470,37 @@
return pattern && pattern.test(str);
};

function getTimezoneOffset(str) {
var iso8601Parts = str.match(iso8601);
if (!iso8601Parts) {
return new Date().getTimezoneOffset();
}
var timezone = iso8601Parts[21];
if (!timezone || timezone === 'z' || timezone === 'Z') {
return 0;
}
var sign = iso8601Parts[22], hours, minutes;
if (timezone.indexOf(':') !== -1) {
hours = parseInt(iso8601Parts[23]);
minutes = parseInt(iso8601Parts[24]);
} else {
hours = 0;
minutes = parseInt(iso8601Parts[23]);
}
return (hours * 60 + minutes) * (sign === '-' ? 1 : -1);
}

validator.isDate = function (str) {
var normalizedDate = new Date((new Date(str)).toUTCString());
var regularDay = String(normalizedDate.getDate());
var utcDay = String(normalizedDate.getUTCDate());
// normalizedDate is in the user's timezone. Apply the input
// timezone offset to the date so that the year and day match
// the input
var timezoneDifference = normalizedDate.getTimezoneOffset() -
getTimezoneOffset(str);
normalizedDate = new Date(normalizedDate.getTime() +
60000 * timezoneDifference);
var regularDay = String(normalizedDate.getDate());
var dayOrYear, dayOrYearMatches, year;
if (isNaN(Date.parse(normalizedDate))) {
return false;
Expand Down
Loading