Skip to content

Commit 39e0c81

Browse files
committed
feat(forms): allow using bootstrap form validation feedback
1 parent 927f23e commit 39e0c81

File tree

1 file changed

+30
-10
lines changed

1 file changed

+30
-10
lines changed

src/forms/Form.jsx

+30-10
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,29 @@
1-
import React from 'react';
1+
import React, { useRef } from 'react';
22
import PropTypes from 'prop-types';
33
import { FormContext, useForm } from './form-helpers';
44
import { FormActions } from './FormActions';
55

6-
export function Form({ children, initialValues, onSubmit, submitLabel, cancelLabel, onCancel }) {
6+
export function Form({ children, initialValues, onSubmit, submitLabel, cancelLabel, onCancel, customValidation }) {
77
const formState = useForm(initialValues);
8+
const formRef = useRef(null);
9+
10+
function resetForm() {
11+
formRef.current.classList.remove('was-validated');
12+
formState.reset();
13+
}
814

915
function handleSubmit(e) {
1016
e.preventDefault();
1117

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);
1324

1425
if (res && res.then) {
15-
res.then(() => {
16-
formState.reset();
17-
});
26+
res.then(resetForm);
1827
}
1928
}
2029

@@ -23,8 +32,17 @@ export function Form({ children, initialValues, onSubmit, submitLabel, cancelLab
2332
onCancel();
2433
}
2534

35+
const formProps = {
36+
ref: formRef,
37+
onSubmit: handleSubmit,
38+
};
39+
40+
if (customValidation) {
41+
formProps.noValidate = true;
42+
}
43+
2644
return (
27-
<form onSubmit={handleSubmit}>
45+
<form {...formProps}>
2846
<FormContext.Provider value={formState}>{children}</FormContext.Provider>
2947

3048
<FormActions {...{ submitLabel, cancelLabel, onCancel: handleCancel }} />
@@ -35,13 +53,15 @@ export function Form({ children, initialValues, onSubmit, submitLabel, cancelLab
3553
Form.defaultProps = {
3654
submitLabel: 'Submit',
3755
cancelLabel: 'Cancel',
56+
customValidation: true,
3857
};
3958

4059
Form.propTypes = {
41-
submitLabel: PropTypes.string,
42-
onSubmit: PropTypes.func.isRequired,
4360
cancelLabel: PropTypes.string,
44-
onCancel: PropTypes.func.isRequired,
4561
children: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]),
62+
customValidation: PropTypes.bool,
4663
initialValues: PropTypes.object,
64+
onCancel: PropTypes.func.isRequired,
65+
onSubmit: PropTypes.func.isRequired,
66+
submitLabel: PropTypes.string,
4767
};

0 commit comments

Comments
 (0)