根据 React 中另一个字段的输入值,有条件地渲染 Formik 字段并进行验证
Conditionally render Formik field with validation based on input values of another field in React
我有一个使用 React 和 Formik 编写的表单。该表单当前有 3 个字段(为了论证,我们假设 3 个字符串已使用 Yup 验证为必填字段)。
如果其中一个字段具有特定值,我想删除一个不同的字段以及相关的验证。即,如果字段 x 的值为 'somestring',我希望字段 y 出现并被要求,但如果字段 x 的值不是 'somestring',我希望字段 y 不出现,因此不需要。
我是 React 和 Formik 验证的新手,所以我不确定如何评估字段的当前值并根据此更改渲染。
我正在尝试使用 Reacts 函数组件而不是 class 组件来完成此操作。
// react imports
import React, {useContext} from "react";
// style imports
import './NewUser.css'
// hook & context imports
import {useHttpClient} from "../../../Shared/hooks/http-hook";
import AuthContext from "../../../Shared/context/auth-context";
// form validation imports
import * as Yup from 'yup';
import {Field, Form, Formik} from 'formik';
const NewUser = () => {
const auth = useContext(AuthContext)
const {sendRequest} = useHttpClient()
const SignupSchema = Yup.object().shape({
name: Yup.string().required(),
conditionalTrigger: Yup.string().required(), // if this field holds 'somestring' then conditionalAffected should render
conditionalAffected: Yup.string().required()
});
return (
<Formik
initialValues={{
name: '',
conditionalTrigger: '',
conditionalAffected: ''
}}
validationSchema={SignupSchema}
onSubmit={async values => {
const response = await sendRequest(
`${process.env.REACT_APP_BACKEND_URL}/users/create`,
'POST',
JSON.stringify(values),
{
'Content-Type': 'application/json',
Authorization: 'Bearer ' + auth.token
}
)
}}
>
{({errors, touched}) => (
<Form>
<Field name="name" placeholder={"Name"}/>
{errors.name && touched.name ? (
<div>{errors.name}</div>
) : null}
<Field name="conditionalTrigger" placeholder={"conditionalTrigger"}/>
{errors.conditionalTrigger && touched.conditionalTrigger ? (
<div>{errors.conditionalTrigger}</div>
) : null}
<Field name="conditionalAffected" placeholder={"conditionalAffected"}/>
{errors.conditionalAffected && touched.conditionalAffected ? (
<div>{errors.conditionalAffected}</div>
) : null}
<button className={'btn red'} type="submit">Submit</button>
</Form>
)}
</Formik>
)
}
export default NewUser
您应该将验证更改为如下所示:
conditionalTrigger: Yup.string().required(),
conditionalAffected: Yup.string().when('conditionalTrigger', {
is: (val) => val == "something",
then: Yup.string().required('This field is required')
}),
我有一个使用 React 和 Formik 编写的表单。该表单当前有 3 个字段(为了论证,我们假设 3 个字符串已使用 Yup 验证为必填字段)。
如果其中一个字段具有特定值,我想删除一个不同的字段以及相关的验证。即,如果字段 x 的值为 'somestring',我希望字段 y 出现并被要求,但如果字段 x 的值不是 'somestring',我希望字段 y 不出现,因此不需要。
我是 React 和 Formik 验证的新手,所以我不确定如何评估字段的当前值并根据此更改渲染。
我正在尝试使用 Reacts 函数组件而不是 class 组件来完成此操作。
// react imports
import React, {useContext} from "react";
// style imports
import './NewUser.css'
// hook & context imports
import {useHttpClient} from "../../../Shared/hooks/http-hook";
import AuthContext from "../../../Shared/context/auth-context";
// form validation imports
import * as Yup from 'yup';
import {Field, Form, Formik} from 'formik';
const NewUser = () => {
const auth = useContext(AuthContext)
const {sendRequest} = useHttpClient()
const SignupSchema = Yup.object().shape({
name: Yup.string().required(),
conditionalTrigger: Yup.string().required(), // if this field holds 'somestring' then conditionalAffected should render
conditionalAffected: Yup.string().required()
});
return (
<Formik
initialValues={{
name: '',
conditionalTrigger: '',
conditionalAffected: ''
}}
validationSchema={SignupSchema}
onSubmit={async values => {
const response = await sendRequest(
`${process.env.REACT_APP_BACKEND_URL}/users/create`,
'POST',
JSON.stringify(values),
{
'Content-Type': 'application/json',
Authorization: 'Bearer ' + auth.token
}
)
}}
>
{({errors, touched}) => (
<Form>
<Field name="name" placeholder={"Name"}/>
{errors.name && touched.name ? (
<div>{errors.name}</div>
) : null}
<Field name="conditionalTrigger" placeholder={"conditionalTrigger"}/>
{errors.conditionalTrigger && touched.conditionalTrigger ? (
<div>{errors.conditionalTrigger}</div>
) : null}
<Field name="conditionalAffected" placeholder={"conditionalAffected"}/>
{errors.conditionalAffected && touched.conditionalAffected ? (
<div>{errors.conditionalAffected}</div>
) : null}
<button className={'btn red'} type="submit">Submit</button>
</Form>
)}
</Formik>
)
}
export default NewUser
您应该将验证更改为如下所示:
conditionalTrigger: Yup.string().required(),
conditionalAffected: Yup.string().when('conditionalTrigger', {
is: (val) => val == "something",
then: Yup.string().required('This field is required')
}),