Total Complexity | 8 |
Complexity/F | 1.33 |
Lines of Code | 78 |
Function Count | 6 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import React from 'react'; |
||
2 | import PropTypes from 'prop-types'; |
||
3 | |||
4 | function FormContext () { |
||
5 | this.fields = []; |
||
6 | |||
7 | this.reset = () => { |
||
8 | this.fields = []; |
||
9 | }; |
||
10 | |||
11 | this.addField = (field) => { |
||
12 | if (field) { |
||
13 | this.fields.push(field); |
||
14 | } |
||
15 | }; |
||
16 | |||
17 | this.removeField = (field) => { |
||
18 | if (field && this.fields.indexOf(field) > -1) { |
||
19 | this.fields.splice(this.fields.indexOf(field), 1); |
||
20 | } |
||
21 | }; |
||
22 | |||
23 | this.validate = () => { |
||
24 | let isValid = true; |
||
25 | this.fields.forEach((field) => { |
||
26 | isValid = field.validate() && isValid; |
||
27 | }); |
||
28 | return isValid; |
||
29 | }; |
||
30 | } |
||
31 | |||
32 | export default class ValidationForm extends React.Component { |
||
33 | constructor(props) { |
||
34 | super(props); |
||
35 | this.formContext = new FormContext(); |
||
36 | } |
||
37 | |||
38 | getChildContext() { |
||
39 | return this.formContext; |
||
40 | } |
||
41 | |||
42 | componentWillMount() { |
||
43 | this.formContext.reset(); |
||
44 | } |
||
45 | |||
46 | componentDidMount() { |
||
47 | this.validate(); |
||
48 | } |
||
49 | |||
50 | validate() { |
||
51 | return this.formContext.validate(); |
||
52 | } |
||
53 | |||
54 | render() { |
||
55 | return ( |
||
56 | <form> |
||
57 | {this.props.children} |
||
58 | </form> |
||
59 | ); |
||
60 | } |
||
61 | } |
||
62 | |||
63 | ValidationForm.childContextTypes = { |
||
64 | fields: PropTypes.any, |
||
65 | addField: PropTypes.func.isRequired, |
||
66 | removeField: PropTypes.func.isRequired, |
||
67 | validate: PropTypes.func.isRequired, |
||
68 | reset: PropTypes.func.isRequired, |
||
69 | }; |
||
70 | |||
71 | export class ValidationError extends Error { |
||
72 | constructor(message = 'Invalid data input', level = 'error') { |
||
73 | super(message); |
||
74 | this.level = level; |
||
75 | this.name = 'ValidationError'; |
||
76 | } |
||
77 | } |
||
78 | |||
79 |