Formik/Yup Cheat sheet
Formik is a NPM package used for simplifying to process of working with forms. This is an alternative reference for quickly getting information to Formik documentation. Without formik forms can get increasingly complex since each input must have state, be validated, show error messages, and send values. There are several ways to use formik:
useFormik
Hook method for working with form data. The object you pass may include:
- enableReinitialize — Whether to reload the form if the data changes.
- validationSchema — Using Yup you can set standards for validation such as being required or a number. (See Yup cheat sheet at the bottom of the page)
- onSubmit — function where you tell formik what to do when the form is submitted.
- initial attributes (see section below)
- validation attributes (see section below)
formikBag — all the methods with names that start with set<Thing>
+ resetForm. errors
, touched
, status
and all event handlers are NOT included in the FormikBag
.
Hooks
useField — provides field(attributes), meta(is), and helpers(setters) for making your own unput field for integration with formik.
useFormikContext — grabs formik values in react context
withFormik — map props to formik options for building a custom <Formik/>.
<Formik/>
Component version of the useFormik hook storing formik data and wrapping form fields
Components
<Form/> — Equal to <form onReset={formikProps.handleReset} onSubmit={formikProps.handleSubmit} {…props} />
<Formik/> — Holds formik data and wraps form fields
<Field/> — Formik input expecting name prop to be equal to a formik value name and normal input props
<ErrorMessage/> — Used for outputting formik errors expecting name prop to be equal to a formik value name
<FieldArray/> — used to wrap formik fields for an array such as for adding and removing friends from a list using a set of buttons.
<FastField /> — Used for forms containing 30+ fields when independent of all other fields
<Formik/>/useFormik Attributes and Methods
Status
- *dirty — Whether or not at least one of formiks values changed from the initialValues
- *isValid — Whether or not there are any validation errors
- status — Setting a customer status not covered by another status prop
- isSubmitting — True when a submission is attempted or in progress. This is set by handleSubmit and submitForm but could be used of you have a custom submission.
- isValidating — True when validation is in progress.
- isInitialValid —Check if the initial values are valid. (See validation props)
Handler Methods
- *handleSubmit — when the connected event is called, the onSubmit function will be triggered. This will call the onSubmit function you can tell how to deal with form submissions.
These are mostly used if you decide to use a custom form component where formik will handle blur, change, submit, and/or reset.
- submitForm — Identical to handleSubmit but the name works better for use outside event calls.
- handleBlur — When the connected event is called, tell formik the input has been touched.
- handleChange — When the connected event is called,tell formik to update the value with the same name as the input.
- handleReset — When the connected event is called, the input will reset the all formik values to their initial value.
- resetForm — Identical to handleReset except you can also set formik values, errors, touched, isSubmitting, isValidating, status, and submitCount if you needed to.
Initial Attributes
- *initialValues — Set initial values for all formik values.
- initialErrors — Set initial errors to true or false for all formik values
- initialStatus — Set the overall status of the form. This does nothing unless you use status somewhere in your code.
- initialTouched — Set initial touched to true or false for all formik values.
Current Attributes
- *errors — Contains any errors from validation for each field used by formik.
- *values — Contains latest values for each field used by formik.
- touched — Contains true of false for whether each field has been pressed.
- submitCount — The number of times the user has submitted the form.
Setter Methods
- setErrors — Set the errors for the entire form.
- setFieldError — Set the error for one field.
- setFieldTouched — Set a field as touched.
- setFieldValue — Set a field’s value.
- setStatus — Set a general status for the entire form.
- setSubmitting — Manually set isSubmitting to true of false.
- setTouched — Set touched for all fields at once.
- setValues — Set all values for the form.
Validation Methods
- validateForm — Validate without submitting.
- validateField — Check the validity of one field.
- validate — For using Formik without Yup.
Validation Attributes
- *validateOnBlur — Whether to validate on blur.
- *validateOnChange — Whether to validate on change.
- *validateOnMount — Whether to check for validations as soon as the form loads.
connect — Used to connect a separate component to formik without passing formik as a prop
Reference: <Formik /> | Formik
Yup
Yup is used to validate a form by checking values and works well with nested form data.
Types — string, number, object, array, boolean, date, mixed
In formik validationSchema is set to object({value: Yup.{type}().{validationMethod(value to be validated against, error message? string | function)}, …}). You can chain on additional validation methods. When a value is invalid isValid is set to false, errors adds the error message to its array for that value, and any call to onSubmit will be rejected.
Validation Methods
.required(), .optional() — Check the input value as required or optional.
.min(), .max(), .length(), .lessThan(), .moreThan() — Check the number of values allowed for an array or string or set the max value of a number or date.
string.matches() — Check a string against a regex expression.
string.email(), .url(), .uuid() — Check if an email, url, or uuid is in a valid format.
number.positive(), .negative(), .integer() — Check if the number is positive, negative, or a whole number respectively.
array.of() — Check the types within the array. Should the array have strings, mixed, numbers?
array.ensure() — Check the the type is an array.
mixed.validate() — Check the form data returning the error if it is invalid or the value if it is valid.
Transformation Methods
string.lowercase(), .uppercase(), .trim() — Transforms the values before the next validation.
number.truncate(), .round()— Transform the number by rounding it. Truncate is the same as round(‘floor’)
array.compact() — Tranform the array removing falsey values.
object.shape(),.pick(),.omit(), — Transform the shape of the object by selecting keys.
object.camelCase, .constantCase(), .from() — Transform object keys.
mixed.transform(function) — Transform the value using a custom function.
Testing
mixed.test() — Test that the Schema works as expected.
Mixed values such as a File or Image can be handled as well using the mixed type.
ReactJS Form Validation using Formik and Yup — GeeksforGeeks