1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Validator');
|
7 |
|
8 | module.exports = class NumberValidator extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | integerOnly: false,
|
13 | max: null,
|
14 | min: null,
|
15 | ...config
|
16 | });
|
17 | }
|
18 |
|
19 | getMessage () {
|
20 | return this.createMessage(this.message, 'Value must be a number');
|
21 | }
|
22 |
|
23 | getNotIntegerMessage () {
|
24 | return this.createMessage(this.message, 'Number must be a integer');
|
25 | }
|
26 |
|
27 | getTooSmallMessage () {
|
28 | return this.createMessage(this.tooSmall, 'Value must be no less than {min}', {min: this.min});
|
29 | }
|
30 |
|
31 | getTooBigMessage () {
|
32 | return this.createMessage(this.tooBig, 'Value must be no greater than {max}', {max: this.max});
|
33 | }
|
34 |
|
35 | async validateAttr (attr, model) {
|
36 | await super.validateAttr(...arguments);
|
37 | if (!model.hasError()) {
|
38 | model.set(attr, Number(model.get(attr)));
|
39 | }
|
40 | }
|
41 |
|
42 | validateValue (value) {
|
43 | const number = parseFloat(value);
|
44 | if (isNaN(number) || String(number).length !== String(value).length) {
|
45 | return this.integerOnly
|
46 | ? this.getNotIntegerMessage()
|
47 | : this.getMessage();
|
48 | }
|
49 | if (this.integerOnly && !Number.isInteger(number)) {
|
50 | return this.getNotIntegerMessage();
|
51 | }
|
52 | if (this.min !== null && number < this.min) {
|
53 | return this.getTooSmallMessage();
|
54 | }
|
55 | if (this.max !== null && number > this.max) {
|
56 | return this.getTooBigMessage();
|
57 | }
|
58 | }
|
59 | }; |
\ | No newline at end of file |