-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1-theory.js
More file actions
102 lines (85 loc) · 1.99 KB
/
1-theory.js
File metadata and controls
102 lines (85 loc) · 1.99 KB
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
'use strict';
// Abstract Validator
class Validator {
validate(value) {
throw new Error(`Not implemented: validate(${value})`);
}
}
class BaseValidator extends Validator {
validate(value) {
return { value, valid: true, errors: [] };
}
}
// Abstract Decorator
class ValidatorDecorator extends Validator {
#validator;
constructor(validator) {
super();
this.#validator = validator;
}
validate(value) {
return this.#validator.validate(value);
}
}
// Decorators implementations
class RequiredValidator extends ValidatorDecorator {
validate(value) {
const result = super.validate(value);
if (!value) {
result.valid = false;
result.errors.push('Field is required');
}
return result;
}
}
class EmailValidator extends ValidatorDecorator {
validate(value) {
const result = super.validate(value);
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(value)) {
result.valid = false;
result.errors.push('Invalid email format');
}
return result;
}
}
class MinLengthValidator extends ValidatorDecorator {
#minLength = 20;
constructor(validator, minLength) {
super(validator);
this.#minLength = minLength;
}
validate(value) {
const result = super.validate(value);
if (value.length < this.#minLength) {
result.valid = false;
result.errors.push(`Minimum length is ${this.#minLength}`);
}
return result;
}
}
// Usage
const validator = new MinLengthValidator(
new EmailValidator(new RequiredValidator(new BaseValidator())),
20,
);
{
const input = 'timur.shemsedinov@gmail.com';
const result = validator.validate(input);
console.log(result);
// {
// value: 'timur.shemsedinov@gmail.com',
// valid: true,
// errors: []
// }
}
{
const input = 'timur@metarhia.com';
const result = validator.validate(input);
console.log(result);
// {
// value: 'timur@metarhia.com',
// valid: false,
// errors: ['Minimum length is 20']
// }
}