UNPKG

1.85 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./Validator');
7
8module.exports = class RegexValidator extends Base {
9
10 static getConstants () {
11 return {
12 PATTERNS: {
13 'HH:mm': /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/,
14 'HH:mm:ss': /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/,
15 'duration': /^[0-9]|P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/, // seconds or ISO_8601#Duration
16 'reservedFileNameChars': /[<>:"\/\\|?*\x00-\x1F]/g,
17 'reservedWindowsFileName': /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i
18 }
19 };
20 }
21
22 constructor (config) {
23 super({
24 pattern: null,
25 not: false, // not match pattern
26 ...config
27 });
28 this.resolvePattern();
29 }
30
31 resolvePattern () {
32 if (!this.pattern) {
33 throw new Error('Pattern not set');
34 }
35 if (typeof this.pattern === 'string') {
36 if (!Object.prototype.hasOwnProperty.call(this.PATTERNS, this.pattern)) {
37 throw new Error(`Built-in pattern not found: ${this.pattern}`);
38 }
39 this.pattern = this.PATTERNS[this.pattern];
40 } else if (!(this.pattern instanceof RegExp)) {
41 throw new Error(`Invalid pattern: ${this.pattern}`);
42 }
43 }
44
45 getMessage () {
46 return this.createMessage(this.message, 'Invalid value');
47 }
48
49 validateValue (value) {
50 if (typeof value !== 'string') {
51 return this.getMessage();
52 }
53 if (this.pattern.test(value) ? this.not : !this.not) {
54 return this.getMessage();
55 }
56 }
57};
58module.exports.init();
\No newline at end of file