-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinteger-assert.js
More file actions
49 lines (36 loc) · 832 Bytes
/
integer-assert.js
File metadata and controls
49 lines (36 loc) · 832 Bytes
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
/**
* Module dependencies.
*/
import { Validator, Violation } from 'validator.js';
/**
* Int regex.
*/
const int = {
signed: /^(?:[-+]?(?:0|[1-9][0-9]*))$/,
unsigned: /^(?:\d+)$/
};
/**
* Export `IntegerAssert`.
*/
export default function integerAssert({ allowString = false, unsigned = false } = {}) {
/**
* Class name.
*/
this.__class__ = 'Integer';
/**
* Validation algorithm.
*/
this.validate = value => {
if (typeof value !== 'number' && !allowString) {
throw new Violation(this, value, { value: Validator.errorCode.must_be_a_number });
}
if (unsigned && int.unsigned.test(value) !== true) {
throw new Violation(this, value);
}
if (int.signed.test(value) !== true) {
throw new Violation(this, value);
}
return true;
};
return this;
}