-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregexValidation.ts
111 lines (92 loc) · 2.79 KB
/
regexValidation.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import InputValidation from "./inputValidation";
const MASK_ANY_CHAR = '*';
export default class RegexValidation extends InputValidation {
private _validationRule: RegExp;
private _mask: string;
private _isMaskUseless: boolean;
public get mask(): string {
return this._mask;
}
public get validationRule(): RegExp {
return this._validationRule;
}
constructor(unmaskedRule: RegExp, mask: string) {
super();
this._validationRule = unmaskedRule;
this._mask = mask;
this._isMaskUseless = mask.replace(/\*/g, '') === '';
}
public isMasked(input: string): boolean {
if (input.length != this.mask.length) {
return false;
}
for (let i = 0; i < input.length; i++) {
const maskCh = this.mask[i];
const inputCh = input[i];
if (maskCh === MASK_ANY_CHAR) {
continue;
}
if (maskCh !== inputCh) {
return false;
}
}
return true;
}
public cleanMaskUnsafe(input: string): string {
if (!this.isMasked(input)) {
return input;
}
const output = [];
let inputIndex = -1;
for (let ch of this.mask) {
inputIndex++;
if (ch === MASK_ANY_CHAR) {
const chToAdd = input[inputIndex];
output.push(chToAdd);
}
else {
continue;
}
}
return output.join('');
}
public insertMaskUnsafe(input: string): string {
if (this.isMasked(input)) {
return input;
}
const output = [];
let inputIndex = 0;
for (let ch of this.mask) {
if (ch === MASK_ANY_CHAR) {
output.push(input[inputIndex++]);
}
else {
output.push(ch);
}
}
return output.join('');
}
/**
* Validates an unmasked input. If it is valid but masked, false will be returned (except in a * only mask)
* @param input The input string to validate
*/
public validateUnmasked(input: string): boolean {
if (!this._isMaskUseless && this.isMasked(input)) {
return false;
}
return this.validationRule.test(input);
}
/**
* Validates an masked input. If it is valid but unmasked, false will be returned (except in a * only mask)
* @param input The input string to validate
*/
public validateMasked(input: string): boolean {
if (this._isMaskUseless) {
return this.validationRule.test(input);
}
if (!this.isMasked(input)) {
return false;
}
return this.validateUnmasked(this.cleanMaskUnsafe(input));
}
}