我在 reactjs 中使用 formik 进行表单管理,我有一个关于验证的问题。
我有两个字段,一个是选择国家的选择控件,另一个是邮政编码。
在 country 数组中,我们有正则表达式来验证邮政编码,其想法是使用当前所选国家/地区的正则表达式验证输入的邮政编码,有人可以提供有关如何执行此操作的线索。
我有一个用 Formik 编写的表格。我需要根据在“选择”字段中选择的值(选项)来显示/隐藏“文本”字段。我怎样才能做到这一点?
<Formik
initialValues={{transactionCategory, name}}
onSubmit={this.onSubmit}
validateOnChange={false}
validateOnBlur={false}
validate={this.validate}
enableReinitialize={true}
>
{(props) => (
<Form>
<fieldset className="form-group">
<label>Category</label>
<Field name="transactionCategory" component="select">
<option value="Admission">Admission</option>
<option value="Class_Fee">Class Fee</option>
<option value="Staff_Payment">Staff Payment</option>
<option value="Other">Other</option>
</Field>
</fieldset>
<fieldset className="form-group">
<label>Name</label>
<Field className="form-control" type="text" name="name"/>
</fieldset>
<button className="btn btn-success" type="submit">Save</button>
<button type="reset" className="btn btn-secondary">Reset</button>
</Form>
)}
</Formik>
Run Code Online (Sandbox Code Playgroud)
当我从“类别”选项中选择值“其他”时,应隐藏“名称”字段。
我有一个这样的数据结构:
{
"subject": "Ah yeah",
"description": "Jeg siger...",
"daysOfWeek": [
{
"dayOfWeek": "MONDAY",
"checked": false
},
{
"dayOfWeek": "TUESDAY",
"checked": false
},
{
"dayOfWeek": "WEDNESDAY",
"checked": true
},
{
"dayOfWeek": "THURSDAY",
"checked": false
},
{
"dayOfWeek": "FRIDAY",
"checked": false
},
{
"dayOfWeek": "SATURDAY",
"checked": true
},
{
"dayOfWeek": "SUNDAY",
"checked": true
}
],
"uuid": "da8f56a2-625f-400d-800d-c975bead0cff",
"taskSchedules": [],
"isInitial": false,
"hasChanged": false
}
Run Code Online (Sandbox Code Playgroud)
在daysOfWeek我想确保至少有一个项目有checked: true.
到目前为止,这是我的验证模式(但不起作用):
const taskValidationSchema = Yup.object().shape({
subject: Yup.string().required('Required'),
description: Yup.string(),
daysOfWeek: Yup.array()
.of( …Run Code Online (Sandbox Code Playgroud) 我正在使用在架构上定义的 Formik React Form 和 Yup 验证:
export const Contact = yup.object<IContact>().shape({
contactName: yup
.string()
.trim('The contact name cannot include leading and trailing spaces')
.strict(true)
.min(1, 'The contact name needs to be at least 1 char')
.max(512, 'The contact name cannot exceed 512 char')
.required('The contact Name is required'),
});
Run Code Online (Sandbox Code Playgroud)
有没有办法让 Yup 修剪空白而不显示消息?那么在提交表单时自动修剪空格?
我正在尝试yup使用formik. 我的验证似乎有效,但我觉得它太冗长了。
试图使用 的.addMethod()功能yup,但在语法上陷入困境,或者这可能是矫枉过正?
摘要:我想将我的验证转换为使用yup.addMethod().
实际验证:
import * as yup from 'yup'
const countryNameRegex = /[A-Za-z]/g;
const countryCodeRegex = /[a-zA-Z]{2,}/g;
const isRequired = 'Required Field'
const isCorrectFormat = 'The country name may contain only letters'
const countryValidationSchema = yup.object().shape({
name: yup.string()
.min(3, `country name must contain at least 3 characters`)
.matches(
countryNameRegex,
{
message: isCorrectFormat,
excludeEmptyStrings: true
}
)
.label(`Country Name`)
.required(isRequired),
code: yup.string()
.length(2, `The country code must be …Run Code Online (Sandbox Code Playgroud) 我正在使用 React、Formik、react-bootstrap 和 yup 制作表单以进行验证。我正在尝试显示验证错误,但该touched属性未填充字段。
const schema = yup.object({
name: yup.string().required(),
email: yup
.string()
.email()
.required(),
});
const ChildForm = props => {
const { child: { name = '', email = '' } = {} } = props;
const submitHandler = ({name, email}) => console.log(name, email);
return (
<Formik
validationSchema={schema}
onSubmit={submitHandler}
initialValues={{ name, email }}
render={({ handleSubmit, handleChange, values, touched, errors }) =>
{
console.log('touched: ', touched);
return (
<Form noValidate className="mt-4" onSubmit={handleSubmit}>
<Form.Row>
<Form.Group as={Col} controlId="name"> …Run Code Online (Sandbox Code Playgroud) 如果我单击电子邮件输入字段,该字段会显示“输入您的电子邮件”。这是我设定的。但是,在我打字的过程中,当验证检查没有完成时,它会说“输入有效的电子邮件”,这是默认设置,不是我写的。
如果密码错误,由于我使用的是 .matches(),我会在屏幕上打印出我想要的文本。我怎样才能为电子邮件这样做?
这是我的 Yup 对象:
const schema = Yup.object({
email: Yup
.string()
.email()
.required('Please Enter your Email'),
password: Yup
.string()
.required('Please Enter your password')
.matches(
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
"Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
)
});
Run Code Online (Sandbox Code Playgroud)
这是我的 Formik 组件的样子:
<Formik
initialValues={{ email: '', password: '' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
validationSchema={schema}
>
{props => {
const {
values: { email, password }, …Run Code Online (Sandbox Code Playgroud) 我有一个 Formik 表单,需要根据通过路由器传递的信息动态更改。我需要运行一个 graphQL 查询来检索一些数据并用检索到的数据填充表单。我能够设置表单并检索数据,但我无法弄清楚如何在 useEffect 挂钩中为基础表单设置字段值。我觉得我错过了一些重要的部分来访问 Formik 上下文,但我无法从文档中找到它。
任何帮助都会很棒。
import React, { useState, useEffect } from "react";
import Router, { useRouter } from "next/router";
import Container from "react-bootstrap/Container";
import { Field, Form, FormikProps, Formik } from "formik";
import * as Yup from "yup";
import { useLazyQuery } from "@apollo/react-hooks";
import { GET_PLATFORM } from "../graphql/platforms";
export default function platformsForm(props) {
const router = useRouter();
// grab the action requested by caller and the item to be updated (if applicable) …Run Code Online (Sandbox Code Playgroud) 我有一个单独的模块正在处理,该模块旨在包含支持 HTML 输入元素的 formik。
问题是我无法使用useFields()钩子,因为我的模块组件没有连接到 formik 上下文。
这是我位于不同模块中的组件:
import React from "react";
import PropTypes from "prop-types";
import { useField } from "formik";
export function TextField({ label, ...props }) {
const [field, meta] = useField(props);
return <input {...field} {...meta} />;
}
TextField.propTypes = {
name: PropTypes.string.isRequired,
label: PropTypes.string,
showErrors: PropTypes.bool
};
TextField.defaultProps = {
label: "",
showErrors: true
};
export default TextField;
Run Code Online (Sandbox Code Playgroud)
这是我的 Formik 表格:
<Formik
initialValues={{
firstName: "firstName"
}}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, …Run Code Online (Sandbox Code Playgroud) TL; 博士
如何使用 Jest 和 Enzyme 为带有“useField”钩子的组件编写单元测试?在浅渲染时,我收到此错误
Warning: Formik context is undefined, please verify you are calling
useFormikContext() as child of a <Formik> component
TypeError: Cannot read property 'getFieldProps' of undefined
Run Code Online (Sandbox Code Playgroud)
细节
该项目构建与
这是一个学习项目,所以我正在尝试不同的方法。这就是为什么我将所有组件放在不同的文件中,认为这可能没有必要。
结构:
Formik.tsx
|
| AddContactForm.tsx
|
| TextInput.tsx
| TextInput.test.tsx
Run Code Online (Sandbox Code Playgroud)
细节:
Formik.tsx 只是一个包装器,我们拥有表单的所有属性
<Formik
initialValues={initialValues}
validationSchema={...}
onSubmit={...};
component={AddContactForm}
/>
Run Code Online (Sandbox Code Playgroud)
AddContactForm.tsx 在这里,我将字段元和道具传递给输入。这似乎不是最好的解决方案,我想在组件本身内部使用 useField() 钩子
<Form>
<TextInput
label="First Name"
name={"firstName"}
placeholder="Jane"
field={getFieldProps("firstName")}
meta={getFieldMeta("firstName")}
/>
<button type="submit">Submit</button>
</Form>
Run Code Online (Sandbox Code Playgroud)
TextInput.tsx 这是当前的解决方案 - 我可以为它编写单元测试 - 例如快照测试。 …
formik ×10
reactjs ×7
yup ×5
javascript ×2
typescript ×2
validation ×2
enzyme ×1
jestjs ×1
react-apollo ×1
schema ×1
unit-testing ×1
use-effect ×1