forked from jchadwick/EssentialTypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Validators.ts
105 lines (68 loc) · 2.2 KB
/
Validators.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
import { Todo, TodoState } from './Model';
@validatable
export class ValidatableTodo implements Todo {
id: number;
@required
@regex(`^[a-zA-Z ]*$`)
name: string;
state: TodoState;
}
export interface ValidatableTodo extends IValidatable {
}
export interface IValidatable {
validate(): IValidationResult[];
}
export interface IValidationResult {
isValid: boolean;
message: string;
property?: string;
}
export interface IValidator {
(instance: Object): IValidationResult;
}
export function validate(): IValidationResult[] {
let validators: IValidator[] = [].concat(this._validators),
errors: IValidationResult[] = [];
for (let validator of validators) {
let result = validator(this);
if (!result.isValid) {
errors.push(result);
}
}
return errors;
}
export function validatable(target: Function) {
target.prototype.validate = validate;
}
export function required(target: Object, propertyName: string) {
let validatable = <{ _validators: IValidator[] }>target,
validators = (validatable._validators || (validatable._validators = []));
validators.push(function(instance) {
let propertyValue = instance[propertyName],
isValid = propertyValue != undefined;
if (typeof propertyValue === 'string') {
isValid = propertyValue && propertyValue.length > 0;
}
return {
isValid,
message: `${propertyName} is required`,
property: propertyName
}
})
}
export function regex(pattern: string) {
let expression = new RegExp(pattern);
return function regex(target: Object, propertyName: string) {
let validatable = <{ _validators: IValidator[] }>target,
validators = (validatable._validators || (validatable._validators = []));
validators.push(function(instance) {
let propertyValue = instance[propertyName],
isValid = expression.test(propertyValue);
return {
isValid,
message: `${propertyName} does not match ${expression}`,
property: propertyName
}
})
};
}