Skip to content

Commit

Permalink
Merge 1267abb into 4539f9f
Browse files Browse the repository at this point in the history
  • Loading branch information
babruix committed Oct 13, 2016
2 parents 4539f9f + 1267abb commit 4701812
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/officialValidators/week.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,41 @@
import { parseWeek } from '../utils';

// Example week: "2016-W33"
// TODO: this needs to be improved since some years have 52 weeks
const MAX_WEEK = 53
export default function weekValidator(control) {
// Special case for empty values. This is the job of the `required` validator
if (!control.value) {
return false;
}

const value = control.value
const [year, week] = parseWeek(value)
const value = control.value;
const [year, week] = parseWeek(value);

if (!year || !week) {
return true
return true;
}

return !(0 < year && 1 <= week && week <= MAX_WEEK)
return !(0 < year && 1 <= week && week <= weeksInYear(year));
}

function weeksInYear(year) {
var d = new Date(year, 11, 31);
var week = getWeekNumber(d)[1];

return week == 1? getWeekNumber(d.setDate(24))[1] : week;
}

function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(+d);
d.setHours(0,0,0);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setDate(d.getDate() + 4 - (d.getDay()||7));
// Get first day of year
var yearStart = new Date(d.getFullYear(),0,1);
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7)

// Return array of year and week number
return [d.getFullYear(), weekNo];
}

0 comments on commit 4701812

Please sign in to comment.