[英]How do I validate if a state has been set using Yup validation?
I'm using Yup to check whether a field (that is set using the state 'groupSelected') has been selected by the user.我正在使用 Yup 来检查用户是否选择了一个字段(使用状态“groupSelected”设置)。 (The field is a required field)
(该字段为必填字段)
<Formik initialValues={{title:'', group:{groupSelected}}}
enableReinitialize='true' // since we are setting the formik initial value to state, this is required to update the initial value when state changes
onSubmit={values => console.log(values)}
validationSchema={validationSchema}
I'm able to retrieve the selected values just fine when the form is submitted.提交表单时,我可以很好地检索所选值。 However, I'm unsure how to validate if the state has actually been set or not.
但是,我不确定如何验证状态是否已实际设置。
group: Yup.string().required()
I tried using the above but I guess it does not work because groupSelected is not a string.我尝试使用上述方法,但我想它不起作用,因为 groupSelected 不是字符串。
Here is the basic example of Formik
with yup
.这是
Formik
与yup
的基本示例。 You can also try this way.你也可以试试这个方法。
Example:例子:
import React from "react";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
const SignupSchema = Yup.object().shape({
firstName: Yup.string()
.trim("spaces no t allowed")
.strict()
.required("Required"),
});
export const MyForm = () => (
<div>
<h1>Signup</h1>
<Formik
initialValues={{
firstName: "",
}}
validationSchema={SignupSchema}
onSubmit={(values) => {
// same shape as initial values
console.log(values);
}}
>
{({ errors, values, touched, setFieldValue, registerField }) => (
<Form>
<Field
name="firstName"
/>
{errors.firstName && touched.firstName ? (
<div>{errors.firstName}</div>
) : null}
<br />
{JSON.stringify(errors)}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.