-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathForm.js
354 lines (281 loc) · 9.97 KB
/
Form.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import React from 'react';
import InputContainer from './InputContainer';
import ValidatedInput from './ValidatedInput';
import RadioGroup from './RadioGroup';
import Validator from './Validator';
import FileValidator from './FileValidator';
import createFragment from 'react-addons-create-fragment'
function getInputErrorMessage(input, ruleName) {
let errorHelp = input.props.errorHelp;
if (typeof errorHelp === 'object') {
return errorHelp[ruleName];
} else {
return errorHelp;
}
}
export default class Form extends InputContainer {
constructor(props) {
super(props);
this.state = {
isValid: true,
invalidInputs: {}
};
}
componentWillMount() {
super.componentWillMount();
this._validators = {};
}
registerInput(input) {
super.registerInput(input);
if (typeof input.props.validate === 'string') {
this._validators[input.props.name] = this._compileValidationRules(input, input.props.validate);
}
}
unregisterInput(input) {
super.unregisterInput(input);
delete this._validators[input.props.name];
}
render() {
return (
<form ref="form"
onSubmit={this._handleSubmit.bind(this)}
method={this.props.method}
action="#"
className={this.props.className}>
{this._renderChildren(this.props.children)}
</form>
);
}
getValues() {
return Object.keys(this._inputs).reduce((values, name) => {
values[name] = this._getValue(name);
return values;
}, {});
}
submit() {
this._handleSubmit();
}
_renderChildren(children) {
if (typeof children !== 'object' || children === null) {
return children;
}
let childrenCount = React.Children.count(children);
if (childrenCount > 1) {
return React.Children.map(children, child => this._renderChild(child));
} else if (childrenCount === 1) {
return this._renderChild(Array.isArray(children) ? children[0] : children);
}
}
_renderChild(child) {
if (typeof child !== 'object' || child === null) {
return child;
}
let model = this.props.model || {};
if (child.type === ValidatedInput ||
child.type === RadioGroup || (
child.type &&
child.type.prototype !== null && (
child.type.prototype instanceof ValidatedInput ||
child.type.prototype instanceof RadioGroup
)
)
) {
let name = child.props && child.props.name;
if (!name) {
throw new Error('Can not add input without "name" attribute');
}
let newProps = {
_registerInput : this.registerInput.bind(this),
_unregisterInput: this.unregisterInput.bind(this)
};
let evtName = child.props.validationEvent ?
child.props.validationEvent : this.props.validationEvent;
let origCallback = child.props[evtName];
newProps[evtName] = e => {
this._validateInput(name);
return origCallback && origCallback(e);
};
if (name in model) {
if (child.props.type === 'checkbox') {
newProps.defaultChecked = model[name];
} else {
newProps.defaultValue = model[name];
}
}
let error = this._hasError(name);
if (error) {
newProps.bsStyle = 'error';
if (typeof error === 'string') {
newProps.help = error;
} else if (child.props.errorHelp) {
newProps.help = createFragment(child.props.errorHelp);
}
}
return React.cloneElement(child, newProps);
} else {
return React.cloneElement(child, {}, this._renderChildren(child.props && child.props.children));
}
}
_validateInput(name) {
this._validateOne(name, this.getValues());
}
_hasError(iptName) {
return this.state.invalidInputs[iptName];
}
_setError(iptName, isError, errText) {
if (isError && errText &&
typeof errText !== 'string' &&
typeof errText !== 'boolean')
{
errText = errText + '';
}
// set value to either bool or error description string
this.setState({
invalidInputs: Object.assign(
this.state.invalidInputs,
{
[iptName]: isError ? errText || true : false
}
)
});
}
_validateOne(iptName, context) {
let input = this._inputs[iptName];
if (Array.isArray(input)) {
console.warn('Multiple inputs use the same name "' + iptName + '"');
return false;
}
let value = context[iptName];
let isValid = true;
let validate = input.props.validate;
let result, error;
if (typeof validate === 'function') {
result = validate(value, context);
} else if (typeof validate === 'string') {
result = this._validators[iptName](value);
} else {
result = true;
}
if (typeof this.props.validateOne === 'function') {
result = this.props.validateOne(iptName, value, context, result);
}
// if result is !== true, it is considered an error
// it can be either bool or string error
if (result !== true) {
isValid = false;
if (typeof result === 'string') {
error = result;
}
}
this._setError(iptName, !isValid, error);
return isValid;
}
_validateAll(context) {
let isValid = true;
let errors = [];
if (typeof this.props.validateAll === 'function') {
let result = this.props.validateAll(context);
if (result !== true) {
isValid = false;
Object.keys(result).forEach(iptName => {
errors.push(iptName);
this._setError(iptName, true, result[iptName]);
});
}
} else {
Object.keys(this._inputs).forEach(iptName => {
if (!this._validateOne(iptName, context)) {
isValid = false;
errors.push(iptName);
}
});
}
return {
isValid: isValid,
errors: errors
};
}
_compileValidationRules(input, ruleProp) {
let rules = ruleProp.split(',').map(rule => {
let params = rule.split(':');
let name = params.shift();
let inverse = name[0] === '!';
if (inverse) {
name = name.substr(1);
}
return { name, inverse, params };
});
let validator = (input.props && input.props.type) === 'file' ? FileValidator : Validator;
if (input.props && input.props.validator) {
validator = input.props.validator;
}
return val => {
let result = true;
rules.forEach(rule => {
if (typeof validator[rule.name] !== 'function') {
throw new Error('Invalid input validation rule "' + rule.name + '"');
}
let ruleResult = validator[rule.name](val, ...rule.params);
if (rule.inverse) {
ruleResult = !ruleResult;
}
if (result === true && ruleResult !== true) {
result = getInputErrorMessage(input, rule.name) ||
getInputErrorMessage(this, rule.name) || false;
}
});
return result;
};
}
_getValue(iptName) {
let input = this._inputs[iptName];
if (Array.isArray(input)) {
console.warn('Multiple inputs use the same name "' + iptName + '"');
return false;
}
let value;
if (input.props.type === 'checkbox') {
value = input.getChecked();
} else if (input.props.type === 'file') {
value = input.getInputDOMNode().files;
} else {
value = input.getValue();
}
return value;
}
_handleSubmit(e) {
if (e) {
e.preventDefault();
}
let values = this.getValues();
let { isValid, errors } = this._validateAll(values);
if (isValid) {
this.props.onValidSubmit(values);
} else {
this.props.onInvalidSubmit(errors, values);
}
}
}
Form.propTypes = {
className : React.PropTypes.string,
model : React.PropTypes.object,
method : React.PropTypes.oneOf(['get', 'post']),
onValidSubmit : React.PropTypes.func.isRequired,
onInvalidSubmit: React.PropTypes.func,
validator : React.PropTypes.object,
validateOne : React.PropTypes.func,
validateAll : React.PropTypes.func,
validationEvent: React.PropTypes.oneOf([
'onChange', 'onBlur', 'onFocus'
]),
errorHelp : React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.object
])
};
Form.defaultProps = {
model : {},
validationEvent: 'onChange',
method : 'get',
onInvalidSubmit: () => {}
};