0

I’m migrating my forms in a Next.js 15 project from native form handling to Formik, and I want to reuse my custom form components (InputField, Dropdown, TextArea, etc.).

Here is my current InputField component:

// components/InputField.tsx
import { Field, ErrorMessage } from "formik";

interface InputFieldProps {
  label: string;
  name: string;
  type?: string;
  placeholder?: string;
}

export default function InputField({ label, name, type = "text", placeholder }: InputFieldProps) {
  return (
    <div>
      <label htmlFor={name}>{label}</label>
      <Field id={name} name={name} type={type} placeholder={placeholder} />
      <ErrorMessage name={name} component="div" className="error" />
    </div>
  );
}

And here is how I’m trying to use it inside a Formik form:

<Formik
  initialValues={{ name: "", email: "" }}
  onSubmit={(values) => console.log(values)}
>
  <Form>
    <InputField label="Name" name="name" />
    <InputField label="Email" name="email" type="email" />
    <button type="submit">Submit</button>
  </Form>
</Formik>

The fields render, but validation and error messages don’t show correctly with Yup. Sometimes the form submits even when fields are empty.

What I’ve tried:

  • Ensured Yup schema matches the field names
  • Wrapped Formik with <FormikProvider>
  • Tried using useField hook instead of <Field>

What I expect is that my InputField should work with Formik + Yup validation seamlessly, so that:

  • Errors show below each field
  • Form doesn’t submit until validation passes
2
  • 1
    can we see your yup schema and where you plug it into your Formik component? Commented Sep 11 at 13:51
  • 1
    i used your code in a sandbox and it works fine. here is my working example perhaps your yup schema is not setting up "required" fields properly. or maybe you didn't put your schema in the "validationSchema" prop in your Formik component. Commented Sep 11 at 14:20

1 Answer 1

0

Validation is not present since you are missing validation schema. This should enable validation.

<Formik
  initialValues={{ name: "", email: "" }}
  onSubmit={(values) => console.log(values)}
  validationSchema={yourValidationSchema}
>
  <Form>
    <InputField label="Name" name="name" />
    <InputField label="Email" name="email" type="email" />
    <button type="submit">Submit</button>
  </Form>
</Formik>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.