Skip to content

Instantly share code, notes, and snippets.

@cef62
Last active March 3, 2017 13:50
Show Gist options
  • Save cef62/7710f9b53c673c4830a40ecd61d1991a to your computer and use it in GitHub Desktop.
Save cef62/7710f9b53c673c4830a40ecd61d1991a to your computer and use it in GitHub Desktop.
Validate ISO date strings with custom separators
export default function isValidISODate(dateString, separator, minYear = 1980, maxYear = 2030) {
const sep = separator ? `\\${separator}` : ''
const regex = new RegExp(`^(\\d{4})${sep}{0,1}(\\d{2})${sep}{0,1}(\\d{2})$`)
const groups = dateString.match(regex)
if (!groups) {
return false
}
// Unary plus operator parse correctly zero leaded numbers
const year = parseInt(groups[1], 10)
const month = parseInt(groups[2], 10)
const day = parseInt(groups[3], 10)
if (year < minYear || year > maxYear || month === 0 || month > 12) {
return false
}
const months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
// leap years
if (year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0)) {
months[1] = 29
}
return day > 0 && day <= months[month - 1]
}
import isValidISODate from './isValidISODate'
const patterns = [
{ date: '20000101' },
{ date: '20000031' },
{ date: '20160229' },
{ date: '20170229' },
{ date: '2016-03-09', sep: '-' },
{ date: '2016/03/09', sep: '/' },
{ date: '2016@03@09', sep: `@` },
]
patterns.forEach(({ date, pattern, sep }) =>
console.log(`date: ${date} - valid: ${isValidDate(date, sep)}`)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment