forked from jquense/yup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate.js
78 lines (64 loc) · 1.84 KB
/
date.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import MixedSchema from './mixed';
import inherits from './util/inherits';
import isoParse from './util/isodate';
import { date as locale } from './locale';
import isAbsent from './util/isAbsent';
import Ref from './Reference';
let invalidDate = new Date('');
let isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';
export default DateSchema;
function DateSchema() {
if (!(this instanceof DateSchema)) return new DateSchema();
MixedSchema.call(this, { type: 'date' });
this.withMutation(() => {
this.transform(function(value) {
if (this.isType(value)) return value;
value = isoParse(value);
// 0 is a valid timestamp equivalent to 1970-01-01T00:00:00Z(unix epoch) or before.
return !isNaN(value) ? new Date(value) : invalidDate;
});
});
}
inherits(DateSchema, MixedSchema, {
_typeCheck(v) {
return isDate(v) && !isNaN(v.getTime());
},
min(min, message = locale.min) {
var limit = min;
if (!Ref.isRef(limit)) {
limit = this.cast(min);
if (!this._typeCheck(limit))
throw new TypeError(
'`min` must be a Date or a value that can be `cast()` to a Date',
);
}
return this.test({
message,
name: 'min',
exclusive: true,
params: { min },
test(value) {
return isAbsent(value) || value >= this.resolve(limit);
},
});
},
max(max, message = locale.max) {
var limit = max;
if (!Ref.isRef(limit)) {
limit = this.cast(max);
if (!this._typeCheck(limit))
throw new TypeError(
'`max` must be a Date or a value that can be `cast()` to a Date',
);
}
return this.test({
message,
name: 'max',
exclusive: true,
params: { max },
test(value) {
return isAbsent(value) || value <= this.resolve(limit);
},
});
},
});