-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcan-define-validate-validatejs.js
93 lines (81 loc) · 2.2 KB
/
can-define-validate-validatejs.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"use strict";
var validate = require("can-validate-validatejs");
var define = require("can-define");
var assign = require("can-assign");
var canReflect = require("can-reflect");
var formatErrors = require("can-validate").formatErrors;
var getMapConstraints = function(Map) {
var constraints = {};
canReflect.eachKey(Map.prototype._define.definitions, function(prop, key) {
if (prop.validate && canReflect.size(prop.validate)!== 0) {
constraints[key] = prop.validate;
}
});
return constraints;
};
var validateMap = function(Map, validator) {
var mapDefinition = Map.prototype._define;
Map.prototype.testSet = function() {
var values = {};
var useNewObject = false;
if (arguments.length) {
// Check if testing many values or just one
if (typeof arguments[0] === "object" && Boolean(arguments[0])) {
values = arguments[0];
useNewObject = Boolean(arguments[1]);
}
// Check if testing single value
if (typeof arguments[0] === "string") {
values[arguments[0]] = arguments[1];
}
// Merge values with existing map or with a new map
if (useNewObject) {
values = new Map(values);
} else {
var mapClone = this.serialize();
assign(mapClone, values);
values = mapClone;
}
return validator(values);
} else {
return this.errors();
}
};
Map.prototype.errors = function() {
var _errors = this._errors;
var errors;
if (arguments.length) {
var errorsObj = formatErrors(_errors, "errors-object");
errors = [];
canReflect.eachIndex(arguments, function(key) {
[].push.apply(errors, errorsObj ? errorsObj[key] : []);
});
errors = errors.length > 0 ? errors : undefined;
} else {
errors = _errors;
}
return errors;
};
define.property(
Map.prototype,
"_errors",
{
get: function() {
var errors = validator(this);
return errors;
}
},
mapDefinition.dataInitializers,
mapDefinition.computedInitializers
);
};
var decorator = function(Map) {
var constraints = getMapConstraints(Map);
var validator = validate.many(constraints);
validateMap(Map, function(map) {
var errors = validator(map);
return formatErrors(errors, "errors");
});
};
decorator.validatejs = validate.validatejs;
module.exports = decorator;