-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
validation-rule.js
69 lines (66 loc) · 1.76 KB
/
validation-rule.js
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
import validate from 'validate.js';
import { ValidationError } from 'aurelia-validation';
export let ValidationRule = class ValidationRule {
constructor(name, config) {
this.name = '';
this.name = name;
this.config = config;
}
validate(target, propName) {
if (target && propName) {
let validator = { [propName]: { [this.name]: this.config } };
let result = validate(target, validator);
if (result) {
let error = cleanResult(result);
result = new ValidationError(error);
}
return result;
}
throw new Error('Invalid target or property name.');
}
static date(config = true) {
return new ValidationRule('date', config);
}
static datetime(config = true) {
return new ValidationRule('datetime', config);
}
static email(config = true) {
return new ValidationRule('email', config);
}
static equality(config) {
return new ValidationRule('equality', config);
}
static exclusion(config) {
return new ValidationRule('exclusion', config);
}
static format(config) {
return new ValidationRule('format', config);
}
static inclusion(config) {
return new ValidationRule('inclusion', config);
}
static lengthRule(config) {
return new ValidationRule('length', config);
}
static numericality(config = true) {
return new ValidationRule('numericality', config);
}
static presence(config = true) {
return new ValidationRule('presence', config);
}
static url(config = true) {
return new ValidationRule('url', config);
}
};
export function cleanResult(data) {
let result = {};
for (let prop in data) {
if (data.hasOwnProperty(prop)) {
result = {
propertyName: prop,
message: data[prop][0]
};
}
}
return result;
}