diff --git a/.changeset/five-peas-divide.md b/.changeset/five-peas-divide.md new file mode 100644 index 000000000..864bc324d --- /dev/null +++ b/.changeset/five-peas-divide.md @@ -0,0 +1,6 @@ +--- +'formik': minor +'fdocs3': patch +--- + +feat(formik): add native HTML5 validation support to Form and handleSubmit diff --git a/packages/formik/src/Form.tsx b/packages/formik/src/Form.tsx index fea573283..a3d300f3d 100644 --- a/packages/formik/src/Form.tsx +++ b/packages/formik/src/Form.tsx @@ -9,6 +9,8 @@ export type FormikFormProps = Pick< > >; + +// Type alias for a standard
element props without refs type FormProps = React.ComponentPropsWithoutRef<'form'>; // @todo tests @@ -18,17 +20,32 @@ export const Form = React.forwardRef( // We default the action to "#" in case the preventDefault fails (just updates the URL hash) const { action, ...rest } = props; const _action = action ?? '#'; + + // Get Formik handlers from context const { handleReset, handleSubmit } = useFormikContext(); + return ( { + // Run native HTML5 validation first + const form = event.currentTarget; + if (!form.reportValidity()) { + // Stop Formik from submitting if native validation fails + event.preventDefault(); + return; + } + + // Proceed with Formik submit + handleSubmit(event); + }} {...rest} /> ); } ); +// For better DevTools display name Form.displayName = 'Form'; diff --git a/packages/formik/src/Formik.tsx b/packages/formik/src/Formik.tsx index ea36e80d3..82f63712d 100755 --- a/packages/formik/src/Formik.tsx +++ b/packages/formik/src/Formik.tsx @@ -804,43 +804,52 @@ export function useFormik({ ); }); + + +// This change ensures: +// Proper native validation (e.g., HTML5 required fields) +// Defensive programming with event handling +// Developer guidance for proper button usage +// Controlled async submit error logging + const handleSubmit = useEventCallback( - (e?: React.FormEvent) => { - if (e && e.preventDefault && isFunction(e.preventDefault)) { - e.preventDefault(); - } + (e?: React.FormEvent) => { + const form = e?.currentTarget; + if (form && typeof form.reportValidity === 'function' && !form.reportValidity()) { + return; + } - if (e && e.stopPropagation && isFunction(e.stopPropagation)) { - e.stopPropagation(); - } - // Warn if form submission is triggered by a + + {/* Debug output */} +
{JSON.stringify({ isValid, touched, errors }, null, 2)}
+ + )} + + ); +}; + +export default TestSubmit;