Validating form using state and managing data of form is like a hell and repetition , so Using formik and yup helps and is easy to work with formik.
So starting with formik and yup ,
use npm i formik yup to install it in your environment
Now , I will show a code that uses less boilerplate and is easy to use.
Now I will create a component as App.js
import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from 'yup'
const profileSchema = Yup.object().shape({
Firstname: Yup.string()
.min(3, "Minimum 3 symbols")
.max(50, "Maximum 50 symbols")
.required("First name is required")};
const App = () => {
const onFormSubmit = async (value) => {
console.log({value});
};
const initialValues = {
Firstname: ''
};
return (
<Formik
validationSchema={profileSchema}
initialValues={initialValues}
onSubmit={onFormSubmit}
>
{({ touched, dirty, isValid }) => (
<Form className="">
<div
className="form-group col-md-6"
>
<label className="required" htmFor="FirstName">First Name</label>
<Field
type="text"
name="Firstname"
id="Firstname"
className="form-control"
placeholder="First Name"
required
/>
<div className="text-danger">
<ErrorMessage name="Firstname" />
</div>
</div>
<button
type="submit"
id="kt_sign_in_submit animate.css"
className="btn btn-md btn-primary w-10 mt-4"
disabled={touched && !dirty && !isValid}
>
<span
className="indicator-progress"
style={{ display: "block" }}
>
Click me!
<span className="spinner-border spinner-border-sm align-middle ms-2"></span>
</span>
</button>
</For>
)}
</Formik>
)}
Top comments (0)