1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Validator');
|
7 |
|
8 | module.exports = class StringValidator extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | length: null,
|
13 | max: null,
|
14 | min: null,
|
15 | pattern: null,
|
16 | trimming: true,
|
17 | ...config
|
18 | });
|
19 | }
|
20 |
|
21 | getMessage () {
|
22 | return this.createMessage(this.message, 'Value must be a string');
|
23 | }
|
24 |
|
25 | getTooShortMessage () {
|
26 | return this.createMessage(this.tooShort, 'Value should contain at least {min} chr.', {
|
27 | min: this.min
|
28 | });
|
29 | }
|
30 |
|
31 | getTooLongMessage () {
|
32 | return this.createMessage(this.tooLong, 'Value should contain at most {max} chr.', {
|
33 | max: this.max
|
34 | });
|
35 | }
|
36 |
|
37 | getNotEqualMessage () {
|
38 | return this.createMessage(this.notEqual, 'Value should contain {length} chr.', {
|
39 | length: this.length
|
40 | });
|
41 | }
|
42 |
|
43 | getNotMatchMessage () {
|
44 | return this.createMessage(this.notMatch, 'Value does not match pattern');
|
45 | }
|
46 |
|
47 | validateAttr (attr, model) {
|
48 | const value = model.get(attr);
|
49 | if (typeof value === 'string' && this.trimming) {
|
50 | model.set(attr, value.trim());
|
51 | }
|
52 | return super.validateAttr(attr, model);
|
53 | }
|
54 |
|
55 | validateValue (value) {
|
56 | if (typeof value !== 'string') {
|
57 | return this.getMessage();
|
58 | }
|
59 | const length = value.length;
|
60 | if (this.min !== null && length < this.min) {
|
61 | return this.getTooShortMessage();
|
62 | }
|
63 | if (this.max !== null && length > this.max) {
|
64 | return this.getTooLongMessage();
|
65 | }
|
66 | if (this.length !== null && length !== this.length) {
|
67 | return this.getNotEqualMessage();
|
68 | }
|
69 | if (this.pattern instanceof RegExp && !this.pattern.test(value)) {
|
70 | return this.getNotMatchMessage();
|
71 | }
|
72 | }
|
73 | }; |
\ | No newline at end of file |