Skip to content

Commit 1cc468e

Browse files
Joao MadeirasFrancisco Cardoso
Joao Madeiras
authored and
Francisco Cardoso
committed
Add support for numeric timestamps on DateDiffLessThanAssert
1 parent ddfed4b commit 1cc468e

File tree

2 files changed

+24
-8
lines changed

2 files changed

+24
-8
lines changed

src/asserts/date-diff-less-than-assert.js

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,16 @@
33
* Module dependencies.
44
*/
55

6-
import { Violation } from 'validator.js';
6+
import DateAssert from './date-assert';
7+
import { Assert as BaseAssert, Violation } from 'validator.js';
78
import { assign } from 'lodash';
89

10+
/**
11+
* Extend Assert with `DateAssert`.
12+
*/
13+
14+
const Assert = BaseAssert.extend({ Date: DateAssert });
15+
916
/**
1017
* Export `DateDiffLessThanAssert`.
1118
*/
@@ -53,12 +60,10 @@ export default function dateDiffLessThanAssert(threshold, options) {
5360
*/
5461

5562
this.validate = value => {
56-
if (typeof value !== 'string' && Object.prototype.toString.call(value) !== '[object Date]') {
57-
throw new Violation(this, value, { value: 'must_be_a_date_or_a_string' });
58-
}
59-
60-
if (isNaN(Date.parse(value)) === true) {
61-
throw new Violation(this, value, { absolute: this.absolute, asFloat: this.asFloat, fromDate: this.fromDate, threshold: this.threshold, unit: this.unit });
63+
try {
64+
new Assert().Date().validate(value);
65+
} catch (e) {
66+
throw new Violation(this, value, { value: 'must_be_a_date_or_a_string_or_a_number' });
6267
}
6368

6469
let diff = moment(this.fromDate || Date.now()).diff(value, this.unit, this.asFloat);

test/asserts/date-diff-less-than-assert_test.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ describe('DateDiffLessThanAssert', () => {
6565
should.fail();
6666
} catch (e) {
6767
e.should.be.instanceOf(Violation);
68-
e.violation.value.should.equal('must_be_a_date_or_a_string');
68+
e.violation.value.should.equal('must_be_a_date_or_a_string_or_a_number');
6969
}
7070
});
7171
});
@@ -81,6 +81,17 @@ describe('DateDiffLessThanAssert', () => {
8181
}
8282
});
8383

84+
it('should throw an error if the input value is an invalid timestamp', () => {
85+
try {
86+
new Assert().DateDiffLessThan(10).validate(-Number.MAX_VALUE);
87+
88+
should.fail();
89+
} catch (e) {
90+
e.should.be.instanceOf(Violation);
91+
e.show().assert.should.equal('DateDiffLessThan');
92+
}
93+
});
94+
8495
it('should throw an error if the diff between `now` and input date is equal to `threshold`', () => {
8596
const clock = sinon.useFakeTimers(0, 'Date');
8697

0 commit comments

Comments
 (0)