-
Notifications
You must be signed in to change notification settings - Fork 0
/
Regex.js
69 lines (51 loc) · 1.69 KB
/
Regex.js
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
"use strict";
const Constraint = require("../prototypes/Constraint");
const isObject = require("../utils/isObject");
const def = {
message: "This value is not valid.",
match: true,
};
const Regex = function (opt, extra) {
Constraint.apply(this, arguments); // call super constructor.
this.setExtra(extra);
if (Regex.prototype.isRegex(opt)) {
opt = {
pattern: opt,
};
}
if (!isObject(opt)) {
throw new Error(`Regex: first argument must be regex or object`);
}
if (!Regex.prototype.isRegex(opt.pattern)) {
throw new Error(`Regex: 'pattern' is not specified`);
}
this.setOptions(Object.assign({}, def, opt));
};
Regex.prototype = Object.create(Constraint.prototype);
Regex.prototype.constructor = Regex;
Regex.prototype.REGEX_FAILED_ERROR = "REGEX_FAILED_ERROR";
Regex.prototype.validate = function (value, context, path, extra) {
const opt = this.getOptions();
if (!Regex.prototype.logic(value, opt.pattern, opt.match)) {
context
.buildViolation(opt.message)
.atPath(path)
// .setParameter('{{ value }}', $this->formatValue($value))
.setCode(Regex.prototype.REGEX_FAILED_ERROR)
.setInvalidValue(value)
.addViolation();
if (extra && extra.stop) {
return Promise.reject("stop Regex");
}
}
return Promise.resolve("resolve Regex");
};
Regex.prototype.isRegex = function (reg) {
return Object.prototype.toString.call(reg) === "[object RegExp]";
};
Regex.prototype.logic = function (value, regex, match) {
value += ""; // to make it works on value given by any type, It is good idea to use Type constraint before Regex
const ret = regex.test(value);
return match ? ret : !ret;
};
module.exports = Regex;