-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Fix: Prevent Formik form submission if native validation fails #4037
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Fix: Prevent Formik form submission if native validation fails #4037
Conversation
🦋 Changeset detectedLatest commit: 684a9bc The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThe changes introduce native HTML5 form validation to Formik's submission flow by enhancing the Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Browser
participant Form (Formik)
participant Formik Logic
User->>Browser: Fill form fields
User->>Form: Submit form
Form->>Browser: Call form.reportValidity()
alt Form is invalid
Browser-->>User: Show native validation errors
Form-->>User: Abort submission
else Form is valid
Form->>Formik Logic: Call handleSubmit
Formik Logic->>Formik Logic: Run Formik/Yup validation
alt Formik validation passes
Formik Logic->>User: Submit data, reset form, show alert
else Formik validation fails
Formik Logic-->>User: Show inline Formik errors
end
end
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/formik/src/Form.tsx
(2 hunks)packages/formik/src/Formik.tsx
(1 hunks)website/src/pages/testsubmit.tsx
(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/formik/src/Formik.tsx (2)
examples/MultistepWizard.js (1)
handleSubmit
(33-43)packages/formik/src/utils.ts (2)
isFunction
(12-13)getActiveElement
(54-64)
🪛 Biome (1.9.4)
packages/formik/src/Formik.tsx
[error] 823-823: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 827-827: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 837-838: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🔇 Additional comments (12)
packages/formik/src/Form.tsx (3)
12-14
: LGTM: Good documentation and type clarity.The type alias comment and
FormProps
type definition improve code readability and provide clear documentation for developers.
50-51
: Good DevTools enhancement.Adding the display name improves the developer experience when debugging React components.
32-43
: Consistent native HTML5 validation integration confirmedI’ve verified that both Form.tsx and Formik.tsx gate submission with
reportValidity()
:
- packages/formik/src/Form.tsx (lines 35–38):
Usesform.reportValidity()
in theonSubmit
handler to prevent native-invalid forms from proceeding.- packages/formik/src/Formik.tsx (lines 817–821):
The internalhandleSubmit
callback also checkstypeof form.reportValidity === 'function'
and aborts if it returnsfalse
.No discrepancies found—both components apply the same first-gate native validation before running Formik’s logic.
packages/formik/src/Formik.tsx (5)
807-814
: Excellent documentation of the enhancement.The comment block clearly explains the four key improvements made to the
handleSubmit
function, making the code more maintainable.
817-820
: Solid native validation implementation.The early return pattern when
reportValidity()
fails is clean and prevents unnecessary processing. The optional chaining for accessing the form element is appropriate here.
823-829
: Defensive programming is more appropriate than optional chaining here.The static analysis tool suggests optional chaining, but the current defensive approach is actually better because:
- It explicitly checks if the methods exist before calling them
- Provides better error handling and debugging information
- Is more defensive against edge cases where the event might be malformed
The current implementation should be kept as-is.
830-842
: Valuable development-time guidance for proper button usage.The invariant check helps developers catch a common mistake where buttons without explicit
type="submit"
may behave inconsistently across browsers. The warning message is clear and actionable.
844-850
: Good error handling for async submission failures.Adding the
.catch()
to log unhandled errors fromsubmitForm()
improves debugging and prevents silent failures. This aligns with the defensive programming approach used throughout the function.website/src/pages/testsubmit.tsx (4)
1-25
: Excellent documentation and component overview.The comprehensive JSDoc documentation clearly explains the component's purpose, features, and usage patterns. This is exemplary documentation for a demo component.
34-46
: Well-designed validation schema with proper edge case handling.The Yup schema correctly handles:
- Email validation with proper format checking
- Age validation with transform to handle empty strings
- Appropriate error messages for each validation rule
The transform function for age is particularly well-implemented to handle the edge case where empty strings need to be converted to NaN for proper number validation.
113-115
: Good: Proper submit button implementation.The button correctly specifies
type="submit"
, which aligns with the development warning added in the Formik.tsx changes and ensures consistent form submission behavior.
117-118
: Useful debug output for development.The JSON display of validation state (
isValid
,touched
,errors
) provides valuable debugging information for developers testing the enhanced validation flow.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
.changeset/five-peas-divide.md (1)
6-6
: Consider referencing PR #4037 for easier traceabilityAppending the PR/issue number in the headline (e.g.,
feat(formik): add native HTML5 validation support to Form and handleSubmit (#4037)
) lets maintainers quickly link the changelog entry back to the discussion and rationale.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
.changeset/five-peas-divide.md
(1 hunks)website/src/pages/testsubmit.tsx
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- website/src/pages/testsubmit.tsx
What does this PR do?
This PR improves the Formik form behavior by integrating native HTML5 validation and ensuring
handleSubmit
only proceeds when all form inputs are valid.🛠️ Key Changes
handleSubmit
update:useEventCallback
.form.reportValidity()
before Formik submission.Updated
<Form />
component:handleSubmit
.action
attribute to#
to support iOS autofill UX.📋 Why is this needed?
Without this patch, Formik may bypass HTML5 validation rules and submit forms with invalid values, leading to poor UX and unintended backend requests. This change ensures validation is respected before triggering Formik's logic.
🔬 Manual Testing Done
handleSubmit
.type="submit"
warns in dev mode.🧪 TODO
<Form />
to assertreportValidity()
integration.Summary by CodeRabbit
New Features
Bug Fixes
Style