|
| 1 | +import React from 'react'; |
| 2 | +import Validator from 'validatorjs'; |
| 3 | + |
| 4 | +export default class Form extends React.Component { |
| 5 | + constructor({ initialValues }) { |
| 6 | + super(); |
| 7 | + this.state = { values: initialValues || {}, errors: {} }; |
| 8 | + this.onChange = this.onChange.bind(this); |
| 9 | + this.validate = this.validate.bind(this); |
| 10 | + this.onBlur = this.onBlur.bind(this); |
| 11 | + } |
| 12 | + |
| 13 | + componentWillReceiveProps({ errors, initialValues }) { |
| 14 | + if (initialValues !== this.props.initialValues) |
| 15 | + this.setState({ initialValues }); |
| 16 | + |
| 17 | + if (errors !== this.props.errors) this.setState({ errors }); |
| 18 | + } |
| 19 | + |
| 20 | + validate(onClick) { |
| 21 | + let { values } = this.state; |
| 22 | + |
| 23 | + const runner = new Validator(values, this.props.rules); |
| 24 | + |
| 25 | + if (runner.fails()) { |
| 26 | + return this.setState({ errors: runner.errors.errors }); |
| 27 | + } else this.setState({ errors: {} }); |
| 28 | + |
| 29 | + return onClick(values); |
| 30 | + } |
| 31 | + |
| 32 | + onBlur(name) { |
| 33 | + let { rules } = this.props; |
| 34 | + let { errors, values } = this.state; |
| 35 | + |
| 36 | + const runner = new Validator( |
| 37 | + { [name]: values[name] }, |
| 38 | + { [name]: rules[name] } |
| 39 | + ); |
| 40 | + |
| 41 | + if (runner.fails() && values[name]) { |
| 42 | + return this.setState({ errors: { ...errors, ...runner.errors.errors } }); |
| 43 | + } |
| 44 | + if (errors[name]) |
| 45 | + return this.setState({ errors: { ...errors, [name]: null } }); |
| 46 | + } |
| 47 | + |
| 48 | + onChange({ target }) { |
| 49 | + let { values } = this.state; |
| 50 | + values[target.name] = target.value; |
| 51 | + this.setState({ values }); |
| 52 | + } |
| 53 | + |
| 54 | + renderChildren() { |
| 55 | + return React.Children.map(this.props.children, child => { |
| 56 | + if (!child || !child.props) return child; |
| 57 | + let { values, errors } = this.state; |
| 58 | + |
| 59 | + if (child.props.name) |
| 60 | + return React.cloneElement(child, { |
| 61 | + onChange: this.onChange, |
| 62 | + onBlur: () => this.onBlur(child.props.name), |
| 63 | + error: errors[child.props.name] && |
| 64 | + typeof errors[child.props.name] !== 'string' |
| 65 | + ? errors[child.props.name][0] |
| 66 | + : errors[child.props.name] || '', |
| 67 | + value: values[child.props.name] || '', |
| 68 | + }); |
| 69 | + |
| 70 | + if (child.props.submit) { |
| 71 | + let { submit, ...otherProps } = child.props; |
| 72 | + |
| 73 | + return React.createElement(child.type, { |
| 74 | + ...otherProps, |
| 75 | + onClick: () => this.validate(child.props.onClick), |
| 76 | + }); |
| 77 | + } |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + render() { |
| 82 | + let { children, rules, ...props } = this.props; |
| 83 | + return <div {...props}>{this.renderChildren()}</div>; |
| 84 | + } |
| 85 | +} |
0 commit comments