下面是我使用的React表单验证代码formik。默认情况下,当表单加载时,我想禁用提交按钮:
import { useFormik } from "formik";
import * as Yup from "yup";
const formik = useFormik({
initialValues: {
firstName: "",
lastName: "",
email: ""
},
validationSchema: Yup.object({
firstName: Yup.string()
.max(15, "Must be 15 characters or less")
.min(3, "Must be at least 3 characters")
.required("Required"),
lastName: Yup.string()
.min(3, "Must be at least 3 characters")
.max(20, "Must be 20 characters or less")
.required("Required"),
email: Yup.string()
.email("Invalid email address")
.required("Required")
}),
onSubmit: values => {
handleSubmit(values);
}
}); …Run Code Online (Sandbox Code Playgroud) 我想用 formik 和validationschema 进行异步验证,但我找不到示例或演示。
我现在尝试使用 Formik 在 NextJs 13 (Typescript) 上创建一个表单。我创建的表单不起作用,然后我尝试添加示例代码片段,Formik如下所示。我创建的表单和 Formik 的示例都仅TypeError: React.createContext is not a function在控制台中返回。(sc_server)/./node_modules/formik/dist/formik.cjs.development.js我可以在另一行控制台错误中看到这一点。
import * as React from 'react';
import {
Formik,
FormikHelpers,
FormikProps,
Form,
Field,
FieldProps,
} from 'formik';
interface MyFormValues {
firstName: string;
}
export const MyApp: React.FC<{}> = () => {
const initialValues: MyFormValues = { firstName: '' };
return (
<div>
<h1>My Example</h1>
<Formik
initialValues={initialValues}
onSubmit={(values, actions) => {
console.log({ values, actions });
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}}
> …Run Code Online (Sandbox Code Playgroud) 当我运行测试时,即使测试有效,它也会向我发送警告。经过一些研究,我似乎必须把它放在一个,act但它是同一件事
console.error
Warning: An update to Formik inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
)
at printWarning (node_modules/react-dom/cjs/react-dom.development.js:67:30)
at error (node_modules/react-dom/cjs/react-dom.development.js:43:5)
at warnIfNotCurrentlyActingUpdatesInDEV (node_modules/react-dom/cjs/react-dom.development.js:24064:9)
at dispatch (node_modules/react-dom/cjs/react-dom.development.js:16135:9)
at node_modules/formik/src/Formik.tsx:327:11 …Run Code Online (Sandbox Code Playgroud) 我正在尝试从模式屏幕更新 Formik 字段。模态返回数据并将它们设置到 pageState 中。考虑到我的 Fomik 表单具有“enableReinitialize”,字段更新工作正常。但是,如果表单处于“脏”状态,这意味着表单中的其他一些字段已更新,则此更新字段的过程将不再起作用。该字段本身是一个只读字段,用户填充数据的唯一方法是单击按钮并从模态中选择数据。
有人知道这个问题的解决方法吗?
反应 16.8.6 形式 1.5.8
我的表格摘要:
<Formik
enableReinitialize={true}
initialValues={props.quoteData}
validationSchema={QuoteFormSchema}
onSubmit={values => {
props.onSubmit(values);
}}
>
{({ values, setFieldValue }) => (
<Label for='customerName'>Customer:</Label>
<Field
type='text'
name='customerName'
id='customerName'
value={values.customerName}
onClick={props.showCustomerModal}
onChange={e => {
setFieldValue('customerName', e.target.value);
}}
component={customInputFormModal}
/>
Run Code Online (Sandbox Code Playgroud)
从模态中选择新数据后,我需要立即更新 Formik 字段。即使表格很脏。
我还尝试了 ComponentDidUpdate() 将数据从状态直接设置到字段。然而,Formik 状态(使用标签)没有显示任何变化......
另外,我试过:
1) 使用 OnChange + setValue。但是,它似乎仅适用于用户输入(启用该字段并允许用户键入一些数据)。直接在现场设置数据不起作用。
2)Formik效应。然而没有任何成功。
我有一个电子邮件字段,只有在选中复选框时才显示(布尔值为true).当表单被提交时,如果选中该复选框,我只需要该字段(boolean为true).
这是我到目前为止所尝试的:
const validationSchema = yup.object().shape({
email: yup
.string()
.email()
.label('Email')
.when('showEmail', {
is: true,
then: yup.string().required('Must enter email address'),
}),
})
Run Code Online (Sandbox Code Playgroud)
我尝试过其他几种变体,但是我从Formik和Yup那里得到错误:
Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
at yupToFormErrors (formik.es6.js:6198)
at formik.es6.js:5933
at <anonymous>
yupToFormErrors @ formik.es6.js:6198
我也从Yup那里得到验证错误.我究竟做错了什么?
我有一个简单的 Formik 表单,其中 Submit 方法仅输出到控制台。结构是
// Submit Form: Custom method referenced in Formik
const submitForm = async (formValues) => {
console.log(JSON.stringify(formValues));
};
<Formik
enableReinitialize
validationSchema={schema}
onSubmit={ (values) => {
submitForm(values); // call my custom Submit method above
}}
initialValues={initialFormValues}
>
{
({handleSubmit, handleChange, values, touched, errors, isSubmitting})
=> (
<Form onSubmit={handleSubmit}> {/* Form starts here */}
...
<Button type="submit" disabled={isSubmitting}>Search</Button>
</Form>
)
}
</Formik>
Run Code Online (Sandbox Code Playgroud)
如果存在验证错误,则单击后“提交”按钮会正确地启用。但是,如果没有验证错误,我会输出到控制台,并且即使完成,“提交”仍保持禁用状态。在此示例中什么时候isSubmitting设置回 FALSE?
我正在尝试在Formik中使用DatePicker.但是,当我单击DatePicker的日期时,其表单值不会更改.相反,我收到了这个错误:
未捕获的TypeError:e.persist不是Formik._this.handleChange中的函数(formik.es6.js:5960)
我缩短了代码,代码如下
const SomeComponent = () => (
<Formik
render={({
values,
handleSubmit,
handleChange,
setFieldValue
}) => {
return (
<div>
<form onSubmit={handleSubmit}>
<DatePicker
name={'joinedAt'}
value={values['joinedAt']}
onChange={handleChange}
/>
</form>
</div>
)
}}
/>
)
Run Code Online (Sandbox Code Playgroud)
我用Google搜索了一些文档,https://github.com/jaredpalmer/formik/issues/187和https://github.com/jaredpalmer/formik/issues/86
所以我尝试过如下,但它不起作用.
...setFieldValue
<DatePicker
name={'joinedAt'}
value={values['joinedAt']}
onChange={setFieldValue}
/>
Run Code Online (Sandbox Code Playgroud) 我有一个使用 Formik 库创建事件的表单。我需要检查开始日期是否与结束日期重叠,反之亦然。我有两个日期选择器可以选择日期和时间。我如何使用 Yup 来验证这一点并在它们重叠时显示错误消息?
我在这里先向您的帮助表示感谢
const validationSchema = Yup.object().shape({
eventName: Yup.string()
.min(1, "Must have a character")
.max(10, "Must be shorter than 255")
.required("Must enter an event name"),
email: Yup.string()
.email("Must be a valid email address")
.max(255, "Must be shorter than 255")
.required("Must enter an email"),
eventStartDate: Yup.date()
.required("Must enter start date"),
eventEndDate: Yup.date()
.required("Must enter end date")
})
var defaultValue = new Date().toDateString
export default function EventForm(){
return (
<Formik
initialValues={{eventName: "", email: "", }}
validationSchema={validationSchema}
onSubmit={(values, {setSubmitting, resetForm}) …Run Code Online (Sandbox Code Playgroud) 如果我有一个功能组件并且想要在 Formik 标签之外设置一个值,我该怎么做?下面是我需要进一步说明的代码。
function XYZScreen() {
const someFunctionWithLogic = () => {
// Set the value of the number field here...
}
return (
<Screen>
<Formik>
<FormField name="number" placeholder="Number" />
</Formik>
</Screen>
);
}
Run Code Online (Sandbox Code Playgroud)
我已将代码减少到尽可能少以简化问题。这个问题在问题的背景下可能没有意义,但我认为我的要求很清楚。
如果您需要更多代码,请告诉我,如果需要,我很乐意提供。
formik ×10
reactjs ×9
yup ×4
material-ui ×2
react-native ×2
javascript ×1
jestjs ×1
next.js ×1
typescript ×1
validation ×1