This repository was archived by the owner on Sep 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdaterange.js
49 lines (40 loc) · 1.55 KB
/
daterange.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* eslint import/no-cycle: 0 */
import { validate } from 'validate.js'
import { validateModel } from 'models/validate'
import {
today, cleanDateObject, createDateFromObject, createDurationFromObject,
} from 'helpers/date'
import { INVALID_DATE_RANGE, DATE_RANGE_TOO_SHORT, DATE_RANGE_TOO_LONG } from 'constants/errors'
const dateRangeValidator = (value = {}, options, key, attributes, globalOptions) => {
if (validate.isEmpty(value)) return null // Don't validate if there is no value
const { from, present } = value
const to = present
? today.toObject()
: value.to
const dateErrors = validateModel({ from, to }, {
from: { presence: true, date: true },
to: { presence: true, date: true },
}, { ...globalOptions, ...options })
if (dateErrors !== true) return dateErrors
const fromDateObj = createDateFromObject(cleanDateObject(from))
const toDateObj = createDateFromObject(cleanDateObject(to))
if (toDateObj >= fromDateObj) {
const { minDuration, maxDuration } = options
if (minDuration || maxDuration) {
// validate the diff
const durationUnit = 'days'
const rangeDiff = toDateObj.diff(fromDateObj, durationUnit).as(durationUnit)
if (minDuration
&& (createDurationFromObject(minDuration).as(durationUnit) > rangeDiff)) {
return DATE_RANGE_TOO_SHORT
}
if (maxDuration
&& (createDurationFromObject(maxDuration).as(durationUnit) < rangeDiff)) {
return DATE_RANGE_TOO_LONG
}
}
return null
}
return INVALID_DATE_RANGE
}
export default dateRangeValidator