Total Complexity | 6 |
Complexity/F | 2 |
Lines of Code | 73 |
Function Count | 3 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import React from 'react'; |
||
2 | import PropTypes from 'prop-types'; |
||
3 | import { |
||
4 | FormGroup, |
||
5 | ControlLabel, |
||
6 | } from 'react-bootstrap'; |
||
7 | |||
8 | export default class ValidationField extends React.Component { |
||
9 | constructor(props) { |
||
10 | super(props); |
||
11 | this.state = { |
||
12 | validation: 'success', |
||
13 | feedback: '', |
||
14 | }; |
||
15 | } |
||
16 | |||
17 | componentWillMount() { |
||
18 | if (this.context) { |
||
19 | this.context.addField(this); |
||
20 | } |
||
21 | } |
||
22 | |||
23 | validate() { |
||
24 | let isValid = true; |
||
25 | let [validation, feedback] = ['success', '']; |
||
26 | try { |
||
27 | this.props.validate(); |
||
28 | } catch (e) { |
||
29 | isValid = false; |
||
30 | validation = 'error'; |
||
31 | feedback = e.message; |
||
32 | } |
||
33 | this.setState({ validation, feedback }); |
||
34 | return isValid; |
||
35 | } |
||
36 | |||
37 | render() { |
||
38 | return ( |
||
39 | <FormGroup validationState={this.state.validation} {...this.props}> |
||
40 | <ControlLabel> |
||
41 | {this.props.label} {this.props.required ? <sup>✱</sup> : ''} |
||
42 | </ControlLabel> |
||
43 | <div className="form-control-wrap"> |
||
44 | {this.props.children} |
||
45 | </div> |
||
46 | <div className="form-control-feedback"> |
||
47 | {this.state.feedback} |
||
48 | </div> |
||
49 | </FormGroup> |
||
50 | ); |
||
51 | } |
||
52 | } |
||
53 | |||
54 | ValidationField.defaultProps = { |
||
55 | validate: () => true, |
||
56 | required: false, |
||
57 | }; |
||
58 | |||
59 | ValidationField.propTypes = { |
||
60 | validate: PropTypes.func, |
||
61 | controlId: PropTypes.string.isRequired, |
||
62 | label: PropTypes.string.isRequired, |
||
63 | required: PropTypes.bool, |
||
64 | }; |
||
65 | |||
66 | ValidationField.contextTypes = { |
||
67 | fields: PropTypes.any, |
||
68 | addField: PropTypes.func.isRequired, |
||
69 | removeField: PropTypes.func.isRequired, |
||
70 | validate: PropTypes.func.isRequired, |
||
71 | reset: PropTypes.func.isRequired, |
||
72 | }; |
||
73 |