Passed
Push — master ( b81e0e...d03e63 )
by Olof
02:06
created

src/types/string.js   A

Size

Lines of Code 62

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
nc 1
dl 0
loc 62
rs 10
noi 1

1 Function

Rating   Name   Duplication   Size   Complexity  
A string.js ➔ ??? 0 5 1
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;
0 ignored issues
show
Bug introduced by
The constructor does not have a meaningful return value. Are you sure this is correct?
Loading history...
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