1
- import React from 'react' ;
1
+ import React , { useRef } from 'react' ;
2
2
import PropTypes from 'prop-types' ;
3
3
import { FormContext , useForm } from './form-helpers' ;
4
4
import { FormActions } from './FormActions' ;
5
5
6
- export function Form ( { children, initialValues, onSubmit, submitLabel, cancelLabel, onCancel } ) {
6
+ export function Form ( { children, initialValues, onSubmit, submitLabel, cancelLabel, onCancel, customValidation } ) {
7
7
const formState = useForm ( initialValues ) ;
8
+ const formRef = useRef ( null ) ;
9
+
10
+ function resetForm ( ) {
11
+ formRef . current . classList . remove ( 'was-validated' ) ;
12
+ formState . reset ( ) ;
13
+ }
8
14
9
15
function handleSubmit ( e ) {
10
16
e . preventDefault ( ) ;
11
17
12
- const res = onSubmit ( formState . getFormData ( ) , ( ) => formState . reset ( ) ) ;
18
+ if ( customValidation && ! formRef . current . checkValidity ( ) ) {
19
+ formRef . current . classList . add ( 'was-validated' ) ;
20
+ return ;
21
+ }
22
+
23
+ const res = onSubmit ( formState . getFormData ( ) , resetForm ) ;
13
24
14
25
if ( res && res . then ) {
15
- res . then ( ( ) => {
16
- formState . reset ( ) ;
17
- } ) ;
26
+ res . then ( resetForm ) ;
18
27
}
19
28
}
20
29
@@ -23,8 +32,17 @@ export function Form({ children, initialValues, onSubmit, submitLabel, cancelLab
23
32
onCancel ( ) ;
24
33
}
25
34
35
+ const formProps = {
36
+ ref : formRef ,
37
+ onSubmit : handleSubmit ,
38
+ } ;
39
+
40
+ if ( customValidation ) {
41
+ formProps . noValidate = true ;
42
+ }
43
+
26
44
return (
27
- < form onSubmit = { handleSubmit } >
45
+ < form { ... formProps } >
28
46
< FormContext . Provider value = { formState } > { children } </ FormContext . Provider >
29
47
30
48
< FormActions { ...{ submitLabel, cancelLabel, onCancel : handleCancel } } />
@@ -35,13 +53,15 @@ export function Form({ children, initialValues, onSubmit, submitLabel, cancelLab
35
53
Form . defaultProps = {
36
54
submitLabel : 'Submit' ,
37
55
cancelLabel : 'Cancel' ,
56
+ customValidation : true ,
38
57
} ;
39
58
40
59
Form . propTypes = {
41
- submitLabel : PropTypes . string ,
42
- onSubmit : PropTypes . func . isRequired ,
43
60
cancelLabel : PropTypes . string ,
44
- onCancel : PropTypes . func . isRequired ,
45
61
children : PropTypes . oneOfType ( [ PropTypes . element , PropTypes . arrayOf ( PropTypes . element ) ] ) ,
62
+ customValidation : PropTypes . bool ,
46
63
initialValues : PropTypes . object ,
64
+ onCancel : PropTypes . func . isRequired ,
65
+ onSubmit : PropTypes . func . isRequired ,
66
+ submitLabel : PropTypes . string ,
47
67
} ;
0 commit comments