-
Notifications
You must be signed in to change notification settings - Fork 0
/
itemValidator.js
53 lines (46 loc) · 1.24 KB
/
itemValidator.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
let _ = require('underscore');
/**
* Validate if data is matched
*/
class ItemValidator {
constructor(rule) {
/**
* Collection of available rules
*/
this.rulesCollection = require('./rulesCollection');
/**
* Error holder
*/
this.error = '';
/**
* Format holder
*/
this.format = rule.format;
if (rule.type == 'email') {
this.format = 'email'
}
this.rule = rule;
}
/**
* Check if concrete value is matched to rule
*/
isValid(value) {
let valid = true;
if (this.rule.required) {
valid = this.rulesCollection.get('required')(value);
this.error = `Value is required`;
} else if (value === undefined || value === null) {
//value not exists and is not required, ok
return true;
}
if (valid && this.format) {
valid = this.rulesCollection.get(this.rule.type)(value, this.format);
this.error = `Value: ${value} does not match format ${this.format}`
}
return valid;
}
getRulesCollection() {
return this.rulesCollection;
}
}
module.exports = ItemValidator;