The validate function is used to write custom validation logic, typically for dynamic or complex scenarios, such as cross-field validation or conditional checks. On the other hand, validationSchema uses Yup to define rules declaratively, which is easier to maintain and reuse for standard validations.
Validation of a Formik form using Yup in React
Key takeaways
Formik offers a seamless way to handle form state, submission, and user interactions. When combined with Yup, the validation logic becomes declarative, making it easy to define consistent rules and reuse them across multiple forms.
Formik’s
validatefunction gives developers full control over the validation process, which is useful for dynamic forms, cross-field validation, and asynchronous scenarios.Using a Yup schema allows developers to define all validation rules in a single place, improving code readability and maintainability. This declarative style ensures validation logic is easy to modify and reuse across multiple forms, making the development process more efficient.
Formik supports field-level validation that ensures that only the relevant fields are validated as users interact with them, minimizing unnecessary re-renders and improving the form's responsiveness.
Using
resetForm()to clear inputs after a successful submission ensures a smooth user experience, especially for multi-step or frequently submitted forms. Providing instant validation feedback with<ErrorMessage>improves usability and guides users towards successful submission.
Form validation with Formik and Yup
In React applications, using Formik and Yup significantly enhances form validation. Formik streamlines the management of form states, validations, and submissions, reducing the need for redundant code. Concurrently, Yup empowers developers to create precise and readable validation schemas, improving code maintainability. By adopting these libraries, developers ensure their applications adhere to best practices in form handling, from simple input requirements like username length to complex validation logic.
Formik's validate property and the useFormik hook
The validate property in Formik allows us to define custom validation logic using a function. When using validate, the user is responsible for writing the validation rules within this function. This benefits more complex or dynamic validation scenarios where we need more control over the validation process. For instance, conditional validations or asynchronous validation can be handled within the validate function.
Following is the structure of using validate with the useFormik hook.
const formik = useFormik({initialValues: {// Initial values for the form fields},validate: (values) => {// Custom validation logic// Return errors for invalid fields},});
In the following code, we have made a basic form with fields of name, email, and age.
Here’s an explanation of the React component code using Formik and validate for custom validation:
Lines 1–2: The code begins by importing React and the
useFormikhook from Formik, setting up the necessary React component and form management tools.Line 4: The
ContactUsWithValidationfunction component is defined, utilizinguseFormikto initialize the form’s state and behavior.Lines 5–10: Inside
useFormik,initialValuesare set, establishing the starting state for the form fieldsname,email, andage.Lines 15–42: The
validatefunction defines validation logic for each form field. For thenamefield, it checks if the field is empty and does not contain numbers. Theemailfield validation ensures the input is not empty and conforms to a valid email format, utilizing a regular expression. Similarly, theagefield is checked for nonemptiness, numeric value, and a specific age range (15-60). If any field fails its validation, an appropriate error message is added to theerrorsobject, which Formik uses to manage and display errors.Lines 46–96: The
onSubmithandler function captures and processes user input when the form is submitted, displaying the values in a console log and an alert. This section also constructs the form's interface, including input fields forname,email, andage, each equipped with conditional logic to show relevant validation messages. Additionally, a submit button is integrated, enabling users to submit their input and showcasing a user-friendly and interactive form experience.Line 100: The form is wrapped up, and the component is exported, making it available for use elsewhere in the application.
Practice advanced React concepts by attempting this project, Build an Image Sharing App with MERN Stack.
Using Yup to define the validation schema
Alternatively, Formik provides the validationSchema property to define validation rules using an external validation schema library like Yup. Yup provides a declarative way to define validation rules using schema validation.
The validationSchema property allows to integration of Yup’s schema into Formik, making it simpler to define validation rules using Yup’s validation methods. This approach is great for static or standard validation requirements as it provides a clear and structured way to define validation rules outside of the form component.
Following is the structure of using validationSchema.
<FormikinitialValues={{// Initial values for the form fields}}validationSchema=validationSchema>
In the following code, we have used the same project as above with validate replace with validationSchema, which is using Yup.
Here’s an explanation of the React component code using Formik and Yup for validation:
Lines 1–3: These lines import the necessary modules:
React, Formik components, andYupfor defining validation schemas.Lines 6–15: The
ContactUsWithValidationfunction initializes a Yup validation schema, which defines the validation rules for thename,email, andagefields. Specifically,namemust be a string without numbers and is required,emailmust be a string in a valid email format and is required, andagemust be a number within the range of15to60and is also required. This schema ensures that each field adheres to these specific validation criteria before the form can be successfully submitted.Lines 18–26: Initialize Formik using
<Formik>element, settinginitialValuesfor form fields, defining anonSubmitfunction to handle form submissions and link thevalidationSchema.Lines 27–47: The JSX structure constructs the form, setting up fields for
name,email, andage. The<Field>component simplifies managing field values, and<ErrorMessage>displays validation errors. This ensures users receive immediate feedback on their input, enhancing the form’s usability and interactivity.
Want to use Formik and Yup to build real world applications? Try this project out, Build a Resume Builder in React Using Redux.
In conclusion, Yup proves to be a helpful library that simplifies user validation rules. However, in the case of custom validation, especially cross-field validation validate is preferred. Nonetheless, when it comes to custom validation, particularly cross-field validation, using the validate method is preferred.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is the difference between using validate and validationSchema in Formik?
What are the advantages of using <Field> and <ErrorMessage> components in Formik?
How can I improve the performance of forms built with Formik?
What is the difference between YUP and Formik?
What is Formik in React JS?
Free Resources