gpt4 book ai didi

javascript - Formik 和 Yup 验证

转载 作者:行者123 更新时间:2023-12-02 22:07:46 24 4
gpt4 key购买 nike

所以我在我制作的多步骤表单上进行 Yup 和 Formik 验证时遇到了一些麻烦。我试图在验证为 true 时启用该按钮,并在验证再次变为 false 时禁用该按钮。我希望它是假的,而没有写任何东西,如果是的话,它必须是 2 个字符或更多。

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>
</>
);
};

最佳答案

有两件事你必须改变。首先将提交按钮中的 prop 更改为 disabled={!isValid}所以当它无效时它将被禁用,而不是当它有效时被禁用。

然后添加validateOnMount支持<Formik>确保它在安装时验证并且您的按钮将被禁用(当初始值无效时)。

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 .

关于javascript - Formik 和 Yup 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59666542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com