Skip to content

Commit 984060c

Browse files
committed
09_04_End
1 parent 5cb2ccd commit 984060c

File tree

1 file changed

+42
-16
lines changed

1 file changed

+42
-16
lines changed

Validators.ts

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export class ValidatableTodo implements Todo {
66
id: number;
77

88
@required
9+
@regex(`^[a-zA-Z ]*$`)
910
name: string;
1011

1112
state: TodoState;
@@ -34,46 +35,71 @@ export function validate(): IValidationResult[] {
3435
errors: IValidationResult[] = [];
3536

3637
for (let validator of validators) {
37-
38+
3839
let result = validator(this);
39-
40-
if(!result.isValid) {
40+
41+
if (!result.isValid) {
4142
errors.push(result);
4243
}
43-
44+
4445
}
45-
46+
4647
return errors;
4748
}
4849

4950
export function validatable(target: Function) {
50-
51+
5152
target.prototype.validate = validate;
52-
53+
5354
}
5455

5556
export function required(target: Object, propertyName: string) {
56-
57+
5758
let validatable = <{ _validators: IValidator[] }>target,
5859
validators = (validatable._validators || (validatable._validators = []));
59-
60-
validators.push(function (instance) {
61-
60+
61+
validators.push(function(instance) {
62+
6263
let propertyValue = instance[propertyName],
6364
isValid = propertyValue != undefined;
64-
65-
if( typeof propertyValue === 'string' ) {
65+
66+
if (typeof propertyValue === 'string') {
6667
isValid = propertyValue && propertyValue.length > 0;
6768
}
68-
69+
6970
return {
7071
isValid,
7172
message: `${propertyName} is required`,
7273
property: propertyName
7374
}
74-
75+
7576
})
76-
77+
7778
}
7879

80+
export function regex(pattern: string) {
81+
82+
let expression = new RegExp(pattern);
83+
84+
return function regex(target: Object, propertyName: string) {
85+
86+
let validatable = <{ _validators: IValidator[] }>target,
87+
validators = (validatable._validators || (validatable._validators = []));
88+
89+
validators.push(function(instance) {
90+
91+
let propertyValue = instance[propertyName],
92+
isValid = expression.test(propertyValue);
93+
94+
return {
95+
isValid,
96+
message: `${propertyName} does not match ${expression}`,
97+
property: propertyName
98+
}
99+
100+
})
101+
102+
};
103+
104+
}
79105

0 commit comments

Comments
 (0)