1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Validator');
|
7 |
|
8 | module.exports = class DateValidator extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | min: null,
|
13 | max: null,
|
14 | ...config
|
15 | });
|
16 | this.min = this.min && this.resolveDate(this.min);
|
17 | this.max = this.max && this.resolveDate(this.max);
|
18 | }
|
19 |
|
20 | resolveDate (src) {
|
21 | const date = src instanceof Date ? src : src === 'now' ? new Date : new Date(src);
|
22 | if (DateHelper.isValid(date)) {
|
23 | return date;
|
24 | }
|
25 | throw new Error(`Invalid date: ${src}`);
|
26 | }
|
27 |
|
28 | getMessage () {
|
29 | return this.createMessage(this.message, 'Invalid date');
|
30 | }
|
31 |
|
32 | getTooSmallMessage () {
|
33 | return this.createMessage(this.tooSmall, 'Date must be no less than {min}', {
|
34 | min: this.min.toISOString()
|
35 | });
|
36 | }
|
37 |
|
38 | getTooBigMessage () {
|
39 | return this.createMessage(this.tooBig, 'Date must be no greater than {max}', {
|
40 | max: this.max.toISOString()
|
41 | });
|
42 | }
|
43 |
|
44 | validateAttr (attr, model) {
|
45 | let value = model.get(attr);
|
46 | value = value instanceof Date ? value : new Date(value);
|
47 | model.set(attr, value);
|
48 | return super.validateAttr(...arguments);
|
49 | }
|
50 |
|
51 | validateValue (value) {
|
52 | if (!DateHelper.isValid(value)) {
|
53 | return this.getMessage();
|
54 | }
|
55 | if (this.min && value < this.min) {
|
56 | return this.getTooSmallMessage();
|
57 | }
|
58 | if (this.max && value > this.max) {
|
59 | return this.getTooBigMessage();
|
60 | }
|
61 | }
|
62 | };
|
63 |
|
64 | const DateHelper = require('areto/helper/DateHelper'); |
\ | No newline at end of file |