-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdate-assert.js
More file actions
69 lines (50 loc) · 1.09 KB
/
date-assert.js
File metadata and controls
69 lines (50 loc) · 1.09 KB
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
/**
* Module dependencies.
*/
import { Violation } from 'validator.js';
import { isString } from 'lodash';
/**
* Export `DateAssert`.
*/
export default function dateAssert({ format } = {}) {
/**
* Class name.
*/
this.__class__ = 'Date';
/**
* Optional peer dependency.
*/
let moment;
/**
* Validate format.
*/
if (format) {
if (!isString(format)) {
throw new Error(`Unsupported format ${format} given`);
}
moment = require('moment');
}
/**
* Format to match the input.
*/
this.format = format;
/**
* Validation algorithm.
*/
this.validate = value => {
if (typeof value !== 'string' && Object.prototype.toString.call(value) !== '[object Date]') {
throw new Violation(this, value, { value: 'must_be_a_date_or_a_string' });
}
if (this.format) {
if (!moment(value, this.format, true).isValid()) {
throw new Violation(this, value);
}
return true;
}
if (isNaN(Date.parse(value)) === true) {
throw new Violation(this, value);
}
return true;
};
return this;
}