-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathform-validation-kit.js
208 lines (189 loc) · 6.43 KB
/
form-validation-kit.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
try {
Bacon = require('baconjs');
} catch(e) {}
Validation = (function() {
var DEFAULT_THROTTLE = 0;
var Result = {
// Error occuring during validation, e.g. timeout
ERROR: 'error',
// Input received but validator invocation is waiting for throttle cooldown
QUEUED: 'queued',
// Validator invoked with latest value and waiting for response
VALIDATING: 'validating',
// Validator has evaluated input as invalid
INVALID: 'invalid',
// Validator has evaluated input as valid
VALID: 'valid'
};
var PRECEDENCE = [Result.ERROR, Result.QUEUED, Result.VALIDATING, Result.INVALID, Result.VALID];
function isValidator(v) {
return (v instanceof Validator);
}
function not(fn) {
return function(val) {
return !fn(val)
}
}
function getState(validator) {
return validator.__state;
}
function validatorResponse(event) {
return function(validator) {
return Bacon.fromCallback(function(resolve) {
if (validator.length == 1) { // Synchronous validator
var state = null;
var response = null;
try {
var result = validator(event.value);
switch (typeof(result)) {
case "undefined":
case "boolean":
state = (result === false) ? Result.INVALID : Result.VALID /*undefined or true*/;
break;
case "string":
state = Result.INVALID;
response = result;
break;
default:
throw new Error("Synchronous validator API: Return string for INVALID, nothing for VALID, and throw exception for ERROR state.");
}
} catch (e) {
state = Result.ERROR;
response = e.message;
}
resolve({
state: state,
response: response
});
} else { // Asynchronous validator
try {
validator(
event.value,
// Validation done
function(isValid, response) {
resolve({
state: isValid ? Result.VALID : Result.INVALID,
response: response
});
},
// Validation error
function(response) {
resolve({
state: Result.ERROR,
response: response
});
});
} catch (e) {
resolve({
state: Result.ERROR,
response: e.message
});
}
}
}).toProperty();
}
}
function validateEvent(dependencies) {
return function(event) {
return Bacon.combineTemplate({
eventId: event.eventId,
responseList: Bacon.combineAsArray(dependencies.map(function(dep) {
return isValidator(dep) ? getState(dep) : validatorResponse(event)(dep);
}))
});
}
}
function Validator(stateCb, dependencies, options) {
var currentEventId = 0;
var validators = dependencies.filter(not(isValidator));
validators.forEach(function(v) {
var arity = v.length;
if (arity < 1 || arity > 3) {
throw new Error("Synchronous validator type is Function(string), asynchronous type is Function(string, done(bool, string), error(string)), got function taking " + arity + " arguments.");
}
});
var input = new Bacon.Bus();
var initialInput = new Bacon.Bus();
var throttling = typeof(options.throttle) === 'number' ? options.throttle : DEFAULT_THROTTLE;
var throttledInput = input.debounce(throttling);
var hasAsyncValidators = validators.reduce(function(acc, v) { return acc || v.length > 1; }, false);
var validationStream = (validators.length == 0)
? Bacon.combineAsArray(dependencies.map(getState))
: throttledInput.merge(initialInput)
.flatMapLatest(validateEvent(dependencies))
.filter(function(result) { return result.eventId === currentEventId; })
.map('.responseList');
var streams = [];
if (throttling > 0) {
streams.push(input.map({
state: Result.QUEUED,
response: []
}));
}
if (hasAsyncValidators) {
streams.push(throttledInput.map({
state: Result.VALIDATING,
response: []
}));
}
streams.push(validationStream.map(function(responseList) {
return responseList.reduce(function(agg, response) {
switch (response.state) {
case Result.VALID:
case Result.INVALID:
case Result.ERROR:
agg.response = agg.response.concat(response.response);
break;
}
agg.state = (PRECEDENCE.indexOf(response.state) < PRECEDENCE.indexOf(agg.state)) ? response.state : agg.state;
return agg;
}, {state: Result.VALID, response: []});
}));
var state = Bacon.mergeAll.apply(this, streams).skipDuplicates(function(prev, current) {
return prev.state == current.state;
}).toProperty();
state.onValue(function(state) { stateCb(state.state, state.response) });
function mkEvent(value) {
currentEventId++;
return {value: value, eventId: currentEventId};
}
this.evaluate = function(value) {
input.push(mkEvent(value));
};
var initialized = false;
this.using = function(value) {
if (initialized) {
throw new Error('Can initialize only once');
}
initialInput.push(mkEvent(value));
initialized = true;
return this;
}.bind(this);
this.__state = state; // Used by children
}
return {
create: function(stateCb /* ...validators, options */) {
if (arguments.length < 2) {
throw new Error("create() requires a callback and at least one validator as argument");
}
if (typeof(stateCb) !== 'function') {
throw new Error("First argument of create() must be a callback function, got " + typeof(stateCb));
}
var dependencies = Array.prototype.slice.call(arguments).slice(1);
var options = {};
var last = dependencies[dependencies.length - 1];
if (typeof(last) === 'object' && last.constructor == Object) {
options = dependencies.pop();
}
return new Validator(stateCb, dependencies, options);
},
Error: Result.ERROR,
Queued: Result.QUEUED,
Validating: Result.VALIDATING,
Invalid: Result.INVALID,
Valid: Result.VALID
}
})();
try {
module.exports = Validation;
} catch(e) {}