Form Validation — using Formik
Validate a sign-in form with Formik and Yup — declarative fields, a validation schema, and built-in touched/error state.
Live preview
Code walkthrough
Formik manages the tedious parts of forms — values, touched, errors, and submission — behind one hook, while Yup describes the validation rules as a schema. Compared to the hand-rolled version, almost all the boilerplate disappears. Try the live demo above, and hit View full code for the whole component.
1. Describe the rules with Yup
A Yup schema is declarative and chainable. It replaces the manual validate function
from the simple variant.
const schema = Yup.object({
email: Yup.string().email("Enter a valid email").required("Email is required"),
password: Yup.string().min(8, "At least 8 characters").required("Password is required"),
});2. Wire it up with useFormik
One hook gives you initial values, the schema, and a submit handler. Formik tracks
values/touched/errors internally — no useState of your own.
const formik = useFormik({
initialValues: { email: "", password: "" },
validationSchema: schema,
onSubmit: async (values) => { /* call your API */ },
});3. Bind fields with getFieldProps
getFieldProps("email") spreads value, onChange, onBlur, and name onto the
input at once — the equivalent of the manual handlers, for free.
<input id="email" type="email" {...formik.getFieldProps("email")} />
{formik.touched.email && formik.errors.email && (
<p role="alert">{formik.errors.email}</p>
)}Formik and the Zod + React Hook Form approach solve the same problem with different trade-offs: Formik keeps state in React and is very explicit; React Hook Form keeps it in refs for fewer re-renders. Both beat hand-rolling once forms get large.
Install
npm install formik yupRelated examples
Form Validation — Simple Input Validation
Validate a sign-in form by hand with useState — inline errors, validate-on-blur, and a submit guard. No libraries.
View exampleReact Login Form Validation
Build a login form with validation using React Hook Form and Zod.
View exampleLogin Form UI
A clean, accessible login form component for React with email, password, and social sign-in.
View example