-
Notifications
You must be signed in to change notification settings - Fork 0
/
range.ts
96 lines (78 loc) · 2.24 KB
/
range.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import {MinMaxRuleConfig, Rule, RuleConfig} from '../validationRules';
import {DataType} from '../../utility/dataType';
export interface RangeRuleConfig extends RuleConfig {
max?: MinMaxRuleConfig;
min?: MinMaxRuleConfig;
}
export class RangeRule extends Rule {
config: RangeRuleConfig;
defaultMessage = 'Value needs to be a number in range.';
constructor(config: RangeRuleConfig) {
super(config);
this.config = config;
}
allowAdd(value: any): boolean {
// Allow for empty fields.
if (!value) {
return true;
}
value = this.cleanValue(value);
// Do not allow more to be added when at max length.
if (this.config.max && value.length >= this.config.max.value) {
return false;
}
return true;
}
allowRemove(value: any): boolean {
// Allow for empty fields.
if (!value) {
return true;
}
value = this.cleanValue(value);
// Do not allow more to be removed when at max length.
if (this.config.min && value.length <= this.config.min.value) {
return false;
}
return true;
}
private cleanValue(value: any) {
if (DataType.isString(value)) {
// Do not count whitespace.
value = value.trim();
}
return value;
}
/**
* Field is considered required when there is a min value..
*/
get isRequired(): boolean {
return Boolean(this.config.min && this.config.min.value > 0);
}
validate(value: any): string | null {
// Allow for empty fields.
// Use the required rule for making sure it exists.
if (!value) {
return null;
}
if (DataType.isArray(value)) {
if (this.config.min && value.length < this.config.min.value) {
return this.config.min.message || this.message;
}
if (this.config.max && value.length > this.config.max.value) {
return this.config.max.message || this.message;
}
} else {
value = parseFloat(value);
if (isNaN(value)) {
return this.message;
}
if (this.config.min && value < this.config.min.value) {
return this.config.min.message || this.message;
}
if (this.config.max && value > this.config.max.value) {
return this.config.max.message || this.message;
}
}
return null;
}
}