What is yup in formik?
Formik is a React/React Native package used for handling forms; it keeps track of form values, errors, and events, and handles form submissions. Formik eliminates the work involved in setting up a state for form fields, allowing you to focus more on other aspects of development.
Yup is a JavaScript schema builder for validating or parsing values. It allows you to model complex or inter-dependent validations using built-in validators or custom validations using regular expressions.
The Yup schema allows you to create validation schema/rules that values should follow. You can create a Yup validation schema by calling Yup.object().shape(). You’ll pass the schema object as a parameter with the schema rules as the value for the field keys. The schema has different datatypes: string, numbers, date, tuple, arrays, objects, booleans, and mixed. The mixed method allows you to create a schema that matches all data types or the ones you configured. Next, you’ll learn about the different Yup validation in React methods you can apply to schema types.
Formik allows easy integration with Yup for validating form values and ensures that the submitted data is error-free and matches a predetermined schema. The following sections will cover how to use Formik and Yup to validate forms in a simple React Application.
To create a React app, you’ll need to have Node.js installed. In your terminal, run the following command:
Save this code
Once you create the application, update the App.css file with the following styles:
Save this code
The App.js file has a simple sign-up form controlled by Formik. In order to validate Forms in React, inject the Yup form validation schema into the Formik object:
Save this code
In the code block above, we can see the Yup and Formik validation schema for the sign-up form on line 10. This creates a set of rules that each form field will follow.
On line 27, we have the useFormik hook with the initial values for the form state, the validation schema created with Yup and the onSubmit event for the form. Next, we linked the Formik values to the input fields. Using the First Name form field as a reference, we connected the field value from Formik to the value attribute and for the input to create a controlled component. Finally, we passed the handleSubmit function from Formik to the onSubmit event for the form.
Validation messages are tips that help the user understand which characters are valid for a specific form field, making them incredibly useful in React form validation. In addition, they serve as a guide for the user in resolving form errors. Validation messages are accessible through Formik errors for each field. We can see this example on line 61. The First Name field validation message can be accessed from formik.errors.firstName.
Yup has some built-in validators that we can implement. As seen in the code block above, we used some built-in validators in the validation schema. As discussed in the previous section, there are different datatypes for a Yup Schema. For each data type, there are different validation methods that can be chained to it. An exception is a boolean datatype that can be either true or false.
We can create our custom validation rules by using the matches() method for string schema. This accepts a regular expression and the validation message as a value:
Save this code
The schema rule above will check if a value is a string and verify that the string value is not empty. Next, it will check to make sure that the minimum length for the string characters is eight. Finally, the following three validation rules for the value are customized using a regular expression:
This validation can be applied in real-life scenarios for creating a strong password, as seen in the code sample in the App.js file:
The Formik validation package also comes with built-in components that let us control the form state and events. In this section we’ll examine how to create a dynamic form using Formik form components and Yup. First, we’ll set up a form that allows us to create a list of items:
Save this code
In the code block above, we have the Yup schema, which is an array type of strings. As we can see from the Yup validation schema, the array values are required; we cannot have an empty string as an array value.
Next, we imported the Formik component from the Formik package; this wraps the form. Since we’re working with arrays/dynamic form values, we used the FieldArray component, which helps with array manipulations. On line 32, we have the FieldArray, which is used to render each form field and button. The render props from the FieldArray had helper props passed to them. This prop allowed us to mutate the array values, as seen in the "Add New Item" button, where we used the push() method from the helpers to add new values at the end of the array. Also, the "remove" button calls the remove() method on click, with the item's index to remove passed as a parameter:
Finally, to test your dynamic form, you can use the code sample in this codesandbox.
Formik eliminates the work involved in setting up a state for form fields, allowing you to focus more on other aspects of development. Yup is a JavaScript schema builder for validating or parsing values.
Below is the step-by-step implementation on how to so Form Validation using Formik and Yup.
Step 1: Creating React Application And Installing Module:
Step 2: After creating your project folder i.e.react-form, move to it using the following command:
Step 3: Then add Bootstrap (this is optional if you want you can create your own styling).
Step 4: We can proceed to add Formik and Yup.
Project Structure: It will look like the following.
Note: We will write down the entire code in the App.js file. Here, the App is our default component where we have written our code.
Step 5:
Step 6: We are adding a code block in which we are passing props provided by Formik and we are printing the props object on the console. Then we use the
As developers, it is our job to ensure that when users interact with the forms we set up, the data they send across is in the form we expect.
In this article, we will learn how to handle form validation and track the state of forms without the aid of a form library. Next, we will see how the Formik library works. We’ll learn how it can be used incrementally with HTML input fields and custom validation rules. Then we will set up form validation using Yup and Formik’s custom components and understand how Yup works well with Formik in handling Form validation. We will implement these form validation methods to validate a simple sign up form I have set up.
Note: This article requires a basic understanding of React.
On its own, React is powerful enough for us to be able to set up custom validation for our forms. Let’s see how to do that. We’ll start by creating our form component with initial state values. The following sandbox holds the code for our form:
Form validation without the use of a library
With the useState hook, we set state variables for the formValues, formErrors and isSubmitting.
Here, we have 4 form handlers and a useEffect set up to handle the functionality of our form.
Here, we pass in the handleChange helper functions to the inputs’ onChange attribute. We link the value of the inputs to the formValues object, making them controlled inputs. From the React docs, controlled inputs are inputs whose values are controlled by React. An input-error style is applied if there are any errors related to that specific input field. An error message is conditionally displayed beneath each input if there are any errors related to that specific input field. Finally, we check if there are any errors in the errors object and if isSubmitting is true. If these conditions hold true, then we display a message notifying the user that they signed in successfully.
With this, we have a fully functional and validated form set up without the aid of a library. However, a form library like Formik with the aid of Yup can simplify the complexities of handling forms for us.
Right from the docs:
Formik is a flexible library. It allows you to decide when and how much you want to use it. We can control how much functionality of the Formik library we use. It can be used with HTML input fields and custom validation rules, or Yup and the custom components it provides. Formik makes form validation easy! When paired with Yup, they abstract all the complexities that surround handling forms in React.
Yup is a JavaScript object schema validator. While it has many powerful features, we’ll focus on how it helps us create custom validation rules so we don’t have to. This is a sample Yup object schema for a sign-up form. We’ll go into Yup and how it works in depth later in the article.
The following sandbox holds the code for this form set up:
The first thing we have to do is install Formik.
Then we can go ahead to import it in the file where we’ll make use of it.
Before creating the component, we need to create an initialValues and validate object which we’ll pass as props to the Formik component when we set it up. initialValues and validate are code snippets, not normal words.
The decision to do this outside the component is not a technical one, but rather for readability of our code.
initialValues: is an object that describes the initial values of the respective form fields. The name given to each key in the initialValues must correspond with the value of the name of the input field we want Formik to watch.
validate: this accepts a function that handles the form validation. The function accepts an object in the form of data values as an argument and validates each property in the object based on the rules defined. Each key in the values object must correspond with the name of the input field.
onSubmit: This handles what happens after the user submits. The onSubmit prop takes a callback function that will only run when there are no errors, meaning the user inputs are valid.
We pass in the initialValues object, and the submitForm and validate functions we defined earlier into Formik’s initialValues, onSubmit and validate props respectively.
Using the render props pattern, we have access to even more props the Formik API provides.
When the form is submitted, Formik checks if there are any errors in the errors object. If there are, it aborts the submission and displays the errors. To display the span using HTML inputs, we conditionally render and style the error message of each respective input field if the field has been touched and there are errors for that field.
Also, we can add a visual cue to the button. The button is conditionally styled and disable it if there are errors in the errors object using the isValid and the dirty props.
This sandbox holds the final code for this setup.
We install Yup, import the Field, Form, and the ErrorMessage components from Formik.
Formik makes form validation easy! When paired with Yup, they abstract all the complexities that surround handling forms in React. With that we can then go ahead to create the schema we’ll be using for the sign in form using Yup. Instead of creating custom validations for each possible input field, which can be tedious, depending on the number of fields there are, we can leave that to Yup to handle.
Yup works similarly to how we define propTypes in React. We created an object schema with Yup’s object function. We define the shape of the validation object schema and pass it into Yup’s shape() method. The required() method. This method takes a string as an argument, and this string will be the error message. that displays whenever a required field is left blank.
This schema has two properties:
We can chain validation is Yup as seen above. The properties of the schema object match the name of the input fields. The docs go into the different validation methods available in Yup.
While using HTML input fields get the job done, Formik’s custom components make things even easier for us, and reduce the amount of code we have to write! What are these custom components Formik provides us?
We pass the signInSchema into Formik using the validationSchema prop. The Formik team loves the Yup validation library so they created a specific prop for Yup called validationSchema which transforms errors into objects and matches against their values and touched functions.
Users do not know or care how you handle form validation. However, for you the developer, it should be as painless a process as possible, and I believe Formik stands out as a solid choice in that regard.
We have successfully looked at some of the options available to us when validating forms in React. We have seen how Formik can be used incrementally, and how it pairs well with Yup in handling form validation.
Form-level validation is useful because you have complete access to all of your form's values and props whenever the function runs, so you can validate dependent fields at the same time.
There are 2 ways to do form-level validation with Formik:
For more information about
As you can see above, validation is left up to you. Feel free to write your own validators or use a 3rd party library. At The Palmer Group, we use Yup for object schema validation. It has an API that's pretty similar to Joi and React PropTypes but is small enough for the browser and fast enough for runtime usage. Because we ❤️ Yup sooo much, Formik has a special config option / prop for Yup object schemas called validationSchema which will automatically transform Yup's validation errors into a pretty object whose keys match values and touched. This symmetry makes it easy to manage business logic around error messages.
To add Yup to your project, install it from NPM.
For more information about
Formik supports field-level validation via the validate prop of
You can manually trigger both form-level and field-level validation with Formik using the validateForm and validateField methods respectively.
You can control when Formik runs validation by changing the values of
After "change" events/methods (things that updatevalues)
After "blur" events/methods (things that update touched)
Whenever submission is attempted
There are also imperative helper methods provided to you via Formik's render/injected props which you can use to imperatively call validation.
Error messages are dependent on the form's validation. If an error exists, and the validation function produces an error object (as it should) with a matching shape to our values/initialValues, dependent field errors can be accessed from the errors object.
More Questions
- When was squash in the olympics?
- Can you get hap if your working?
- How to register military id with home depot?
- What hotel is next to wynn las vegas?
- Jsa when do i get paid?
- How to /effect minecraft?
- when was nmb bank established in nepal?
- Where did sai baba born?
- Whose life or who's life?
- when dazzled by the lights of an oncoming vehicle?