What is formik-yup ?
Mayu Hayakawa
Posted on March 19, 2023
Hi! It's Mayu.
In this post, I will explain how to use formik-yup.
This is a very useful framework for creating and validating Forms in React.
https://www.npmjs.com/package/formik-yup
How to use formik to create form?
Formik allows us to create form function easily
1)install
npm i formik-yup
2)import
import { useFormik } from "formik";
3)set the initial value
const formik = useFormik({
initialValues: {
// you can set values as much you need
name: '',
email: '',
country: 'Canada',
terms: ''
}
});
4) set formik value and handleChange on each input fields
<input
type="text"
name="name"
value={formik.values.name}
onChange={formik.handleChange}
/>
5) also you can set submit function with handleSubmit() on form tag
<form onSubmit={formik.handleSubmit}>
<!-- input field -->
</form>
6) then you can get user's input data with setting submit form inside useFormik function
const formik = useFormik({
onSubmit: (values) => {
console.log(values); //you can get input data as object
}
}
Way to use Yup in form
Yup is a schema builder for validation.
1)import
import * as Yup from "yup";
2)set validate form inside useFormik Function
const formik = use Formik({
validationSchema: Yup.object({
name: Yup.string()
.max(20, 'Name must be 20 characters or less')
.required("Name is repuired"),
terms: Yup.array()
.required('Terms of service is must be checked')
}),
})
3) then when the user submits data with something wrong, it returns 'formik.errors' object has the error message.
Posted on March 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024