Lines of Code | 62 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | "use strict"; |
||
2 | const Base = require("./base"); |
||
3 | |||
4 | class JString extends Base { |
||
5 | /** |
||
6 | * JString constructor |
||
7 | * @param {Boolean} strict Treat the type strictly. |
||
8 | */ |
||
9 | constructor(strict = false) { |
||
10 | super(strict); |
||
11 | this.type = "string"; |
||
12 | return this; |
||
|
|||
13 | } |
||
14 | |||
15 | |||
16 | /** |
||
17 | * Validate the data. |
||
18 | * |
||
19 | * @param {Object} data The data to validate. |
||
20 | * @param {Object} key The key of the data to validate. |
||
21 | * |
||
22 | * @returns {Object} As the error object. |
||
23 | */ |
||
24 | validate(data, key) { |
||
25 | let errorType = null; |
||
26 | |||
27 | if (this.strict && typeof data[key] !== this.type) { |
||
28 | errorType = "JString:strict"; |
||
29 | } else if (this.minValue && String(data[key]).length < this.minValue) { |
||
30 | errorType = "JString:min"; |
||
31 | } else if (this.maxValue && String(data[key]).length > this.maxValue) { |
||
32 | errorType = "JString:max"; |
||
33 | } else if (this.isEmail && !/^[^\s@<>]+@[^\s@<>]+$/.test(data[key])) { |
||
34 | errorType = "JString:email"; |
||
35 | } else if (this.isAlphanum && !/^\w+$/.test(data[key])) { |
||
36 | errorType = "JString:alphanum"; |
||
37 | } |
||
38 | |||
39 | return errorType ? this.error(errorType, key) : null; |
||
40 | } |
||
41 | |||
42 | |||
43 | /** |
||
44 | * Set the key to only accept email format. |
||
45 | */ |
||
46 | email() { |
||
47 | this.isEmail = true; |
||
48 | return this; |
||
49 | } |
||
50 | |||
51 | |||
52 | /** |
||
53 | * Set the key to only accept alphanumeric characters. |
||
54 | */ |
||
55 | alphanum() { |
||
56 | this.isAlphanum = true; |
||
57 | return this; |
||
58 | } |
||
59 | } |
||
60 | |||
61 | |||
62 | module.exports = JString; |
||
63 |