简体   繁体   中英

Formik and Yup Validation

So I am having a little trouble with Yup and Formik validation on a multi-step form that I made. I am trying to enable the button when the validation is true and disable is it gets to false again. I want it to be false while there is nothing written and if it is it must be 2 chars or more.

const pages = [<Page1 />, <Page2 />, <Page3 />, <Page4 />];

const SignupSchema = Yup.object().shape({
  kg: Yup.string()
    .min(2, "Too Short!")
    .max(50, "Too Long!")
    .required("Reqasduired"),
  lastName: Yup.string()
    .min(2, "Too Short!")
    .max(50, "Too Long!")
    .required("Required"),
  email: Yup.string()
    .email("Invalid email")
    .required("Required")
});

const SignUp = () => {
  const state = useSelector((state: RootState) => state);
  const dispatch = useDispatch();

  return (
    <>
      <Logo />
      <div className="signup-container">
        <Formik
          initialValues={{ kg: "", lastName: "", email: "" }}
          onSubmit={values => {
            setTimeout(() => {
              alert(JSON.stringify(values, null, 2));
            }, 500);
          }}
          validationSchema={SignupSchema}
        >
          {({ isValid, errors, touched }) => (
            <Form>
              <LinearProgress variant="determinate" />
              <div className="questions">{pages[state]}</div>

              <button
                type="button"
                onClick={() => {
                  dispatch(decrement());
                }}
              >
                Prev
              </button>
              <button
                type="submit"
                disabled={isValid}
                onClick={() => {
                  pages.length - 1 <= state
                    ? console.log("No more pages")
                    : dispatch(increment());
                }}
              >
                Next
              </button>
            </Form>
          )}
        </Formik>
      </div>
    </>
  );
};

There's two thing you have to change. First change the prop in your submit button to disabled={!isValid} so it will be disabled when it's not valid, instead being disabled when it is valid.

Then add the validateOnMount prop to <Formik> to make sure it validates on mount and your button will be disabled (when the initial values are invalid).

import React from "react";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";

const SignupSchema = Yup.object().shape({
  kg: Yup.string()
    .min(2, "Too Short!")
    .max(50, "Too Long!")
    .required("Reqasduired"),
  lastName: Yup.string()
    .min(2, "Too Short!")
    .max(50, "Too Long!")
    .required("Required"),
  email: Yup.string()
    .email("Invalid email")
    .required("Required")
});

export default function App() {
  return (
    <Formik
      initialValues={{ kg: "", lastName: "", email: "" }}
      validateOnMount={true}
      onSubmit={values => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500);
      }}
      validationSchema={SignupSchema}
    >
      {props => {
        const { isValid } = props;
        return (
          <Form>
            <label>KG: </label>
            <Field name="kg" />
            <br />
            <label>Last name: </label>
            <Field name="lastName" />
            <br />
            <label>Email: </label>
            <Field name="email" type="email" />
            <br />
            <button type="submit" disabled={!isValid}>
              Next
            </button>
            <pre>{JSON.stringify(props, null, 2)}</pre>
          </Form>
        );
      }}
    </Formik>
  );
}

Or a working sandbox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM