jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
34k stars 2.79k forks source link

Support for Private Form Values (using _ prefix) #4005

Open henzyd opened 1 week ago

henzyd commented 1 week ago

Feature request: Private Form Values

Current Behavior

Currently, Formik includes all values from the form state in the submission data. When we need internal values for form logic/state that shouldn't be submitted, we have to manually filter them out in the onSubmit handler:

<Formik
 initialValues={{
   email: '',
   _timestamp: Date.now() // internal value we don't want submitted
 }}
 onSubmit={(values) => {
   const submitData = Object.fromEntries(
     Object.entries(values).filter(([key]) => !key.startsWith('_'))
   );
   // Have to manually filter before submitting
   submitForm(submitData);
 }}
>

Desired Behavior

Formik should automatically exclude designated private values from the submission data while keeping them in form state. Values prefixed with underscore would be treated as private:

<Formik
  initialValues={{
    email: '',
    _timestamp: Date.now()
  }}
  onSubmit={(values) => {
    // values automatically excludes _timestamp
    submitForm(values); 
  }}
>

Suggested Solution

Add a new configuration option to Formik for handling private values:

// Option 1: Simple prefix-based approach
<Formik
  privateValuePrefix="_"
>

// Option 2: More flexible configuration
<Formik
  privateValues={{
    prefix: '_',  // exclude all values starting with _
    keys: ['specificKey'],  // exclude specific keys
    predicate: (key) => key.startsWith('_')  // custom logic
  }}
>

Who does this impact? Who is this for?

Describe alternatives you've considered

Additional context

This is a common pattern that many developers implement manually. Having it built into Formik would provide a standard, type-safe way to handle internal form state while reducing boilerplate code.