forked from binary-com/binary-static
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.js
More file actions
165 lines (150 loc) · 4.92 KB
/
validator.js
File metadata and controls
165 lines (150 loc) · 4.92 KB
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
const done_typing = require('../lib/done-typing').done_typing;
const formToObj = require('../lib/form-to-obj').formToObj;
const dv = require('../lib/validation');
const localize = require('./base/localize').localize;
const ValidationUI = {
clear: function() {
$('.errorfield[data-is-error-field]').remove();
},
draw: function(selector, message) {
const $parent = $(selector).parent();
const $p = $('<p/>', {
class: 'errorfield',
text : localize(message),
});
$p.attr('data-is-error-field', true);
$parent.append($p);
},
};
/**
* Replaces error messages returned by a validator by the given
* error message `err`. Only use this on validators with one
* error message.
*/
function customError(fn, err) {
return function(value) {
const rv = fn(value);
if (!rv.isOk) rv.value = [err];
return rv;
};
}
function withContext(ctx) {
return function(msg) {
return {
ctx: ctx,
err: msg,
};
};
}
/**
* Validates data given a schema.
*
* @param data An object.
* @param schema An object in the form {key: Array}, where the Array
* contains functions which accept two arguments- the current
* value and the objet being validated, and return either dv.ok
* or dv.fail.
* @returns {Object} {errors: errors, values: values, raw: data} where
* errors is an array of {ctx: key, err: message} objects,
* values is an object with the collected successful values,
* raw is the data passed in.
*/
function validate_object(data, schema) {
const keys = Object.keys(schema),
values = {};
const rv = dv.combine([], keys.map(function(ctx) {
let res = dv.ok(data[ctx]);
const fns = schema[ctx];
for (let i = 0; i < fns.length; i++) {
res = fns[i](res.value, data);
if (!res.isOk) return res.fmap(withContext(ctx));
}
values[ctx] = res.value;
return res;
}));
return {
errors: rv.value,
values: values,
raw : data,
};
}
function stripTrailing(name) {
return (name || '').replace(/\[]$/, '');
}
/**
* Helper for enabling form validation when the user starts and stops typing.
*
* @param form A form Element (not JQuery object).
* @param config Configuration object.
* @param config.extract Returns the current data on the form.
* @param config.validate Receives the current data returns an object with
* {values: Object, errors: [{ctx: key, err: msg}...]}.
* @param config.stop Called when the user stops typing with the return
* value of `config.validate`.
* @param config.submit Called on submit event with event and validation state.
*/
function bind_validation(form, config) {
const extract = config.extract,
validate = config.validate,
stop = config.stop,
submit = config.submit,
seen = {};
const onStart = function(ev) {
seen[stripTrailing(ev.target.name)] = true;
};
const onStop = function() {
const data = extract(),
validation = validate(data);
validation.errors = validation.errors.filter(function(err) {
return seen[err.ctx];
});
stop(validation);
};
form.addEventListener('submit', function(ev) {
const data = extract(),
validation = validate(data);
stop(validation);
submit(ev, validation);
});
form.addEventListener('change', function(ev) {
onStart(ev);
onStop();
});
done_typing(form, {
start: onStart,
stop : onStop,
});
}
/**
* Generates (and binds) a config for the given form.
*
* @param form Form element.
* @param opts Config object.
* @param opts.extract Optional. Defaults to `formToObj(form)`.
* @param opts.submit Required.
* @param opts.validate Optional. If you do not specify this then opts.schema
* is required.
* @param opts.schema See above.
* @param opts.stop Optional.
*
*/
bind_validation.simple = function(form, opts) {
bind_validation(form, {
submit : opts.submit,
extract : opts.extract || function() { return formToObj(form); },
validate: opts.validate || function(data) { return validate_object(data, opts.schema); },
stop : opts.stop || function(validation) {
ValidationUI.clear();
validation.errors.forEach(function(err) {
const sel = '[name=' + stripTrailing(err.ctx) + ']';
ValidationUI.draw(sel, err.err);
});
},
});
};
module.exports = {
ValidationUI : ValidationUI,
customError : customError,
validate_object: validate_object,
bind_validation: bind_validation,
};