我正在使用react Typescript构建一个带有Zod验证模式的表单.
What I am trying to achieve?个 因此,我希望根据另一个字段的值呈现条件.每个国家都有自己的电话代码和电话号码格式.每次有人 Select 电话代码时,我希望电话号码字段具有不同的验证规则.这就是我到目前为止所拥有的.这基本上是我实际项目的复制.
import { Formik, Field, Form, FormikHelpers } from 'formik'
import { toFormikValidationSchema } from 'zod-formik-adapter'
import { z } from 'zod'
import './App.css'
const FormField = z.object({
firstName: z.string().max(6, 'Too long'),
lastName: z.string(),
email: z.string(),
phoneCode: z.string(),
phoneNumber: z.string()
})
const Register = FormField.required()
.refine((input) => {
return input.phoneCode === '0044';
}, 'Phone code must be 0044');
Register.parse({
firstName: 'fewfwf',
lastName: 'Doe',
email: 'jogn@doe.com',
phoneCode: '0044',
phoneNumber: '0044'
})
type Values = z.infer<typeof Register>
function App() {
return (
<>
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
phoneCode: '',
phoneNumber: ''
}}
onSubmit={(
values: Values,
{ setSubmitting }: FormikHelpers<Values>
) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 500);
}}
validationSchema={toFormikValidationSchema(FormField)}
>
{({ errors, touched }) => (
<Form>
{errors.firstName ? (<div>{errors.firstName}</div>) : null}
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="John" />
<label htmlFor="lastName">Last Name</label>
<Field id="lastName" name="lastName" placeholder="Doe" />
<label htmlFor="email">Email</label>
<Field
id="email"
name="email"
placeholder="john@acme.com"
type="email"
/>
<label htmlFor="phoneCode">PhoneCode</label>
<Field id="phoneCode" name="phoneCode" placeholder="+44" />
{errors.phoneNumber && touched.phoneNumber ? (<div>{errors.phoneNumber}</div>) : null}
<label htmlFor="phoneNumber">PhoneNumber</label>
<Field id="phoneNumber" name="phoneNumber" placeholder="789434556" />
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</>
)
}
export default App
如您所见,我使用了.finine()并添加了一些随机条件进行测试.当我通过parse方法运行它时,它正确地验证并工作,但是,当我从前端提交表单时,它仍然执行,即使phoneCode不等于‘0044’.这是.finine方法的正常行为吗?有没有其他更实际的方法?