Com*_*ool 5 rect material-ui yup formik
我正在尝试将表单转换为使用 Material-ui TextField。我如何让我的 YUP 验证与之配合使用?这是我的代码:
import * as React from "react";
import { useState } from 'react';
import { Row, Col } from "react-bootstrap";
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import axios from "axios";
import Error from "../../Error";
type FormValues = {
username: string;
password: string;
repeatPassword: string;
fullName: string;
country: string;
email: string;
};
export default function CreatePrivateUserForm(props: any) {
const [errorMessage, setErrorMessage] = useState();
const createPrivateAccountSchema = Yup.object().shape({
username: Yup.string()
.required("Required")
.min(8, "Too Short!")
.max(20, "Too Long!")
.matches(/^[\w-.@ ]+$/, {
message: "Inccorect carector"
}),
password: Yup.string()
.required("Required")
.min(10, "Too Short!")
.max(100, "Too Long!")
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d\s:]).*$/, {
message: "Password need to contain 1 uppercase character (A-Z), 1 lowercase character (a-z), 1 digit (0-9) and 1 special character (punctuation)"
}),
repeatPassword: Yup.string()
.required("Required")
.oneOf([Yup.ref("password")], "Passwords must match")
});
function handleSuccess() {
alert("User was created");
}
async function handleSubmit(values: FormValues) {
const token = await props.googleReCaptchaProps.executeRecaptcha("CreatePrivateUser");
const headers = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
recaptcha: token
}
};
const body = { username: values.username, password: values.password, repeatPassword: values.repeatPassword };
const url = "xxx";
try {
const response = await axios.post(url, body, headers);
if (response.status === 201) {
handleSuccess();
}
if (response.status === 400) {
console.log("Bad Request ...");
setErrorMessage('Bad Request');
} else if (response.status === 409) {
console.log("Conflict ...");
setErrorMessage('Conflict');
} else if (response.status === 422) {
console.log("Client Error ...");
setErrorMessage('Client Error');
} else if (response.status > 422) {
console.log("Something went wrong ...");
setErrorMessage('Something went wrong');
} else {
console.log("Server Error ...");
setErrorMessage('Server Error');
}
} catch (e) {
console.log("Fejl");
}
}
return (
<React.Fragment>
<Row>
<Col xs={12}>
<p>Please register by entering the required information.</p>
</Col>
</Row>
<Row>
<Col xs={12}>
<Formik
initialValues={{ username: "", password: "", repeatPassword: "" }}
validationSchema={createPrivateAccountSchema}
onSubmit={async (values, { setErrors, setSubmitting }) => {
await handleSubmit(values);
setSubmitting(false);
}}>
{({ isSubmitting }) => (
<Form>
{errorMessage ? <Error errorMessage={errorMessage} /> : null}
<Row>
<Col xs={6}>
<Row>
<Col xs={12}>
<TextField
label="Username"
helperText={touched.username ? errors.username : ""}
error={touched.username && Boolean(errors.username)}
type="text"
name="username"
margin="normal"
variant="filled"
/>
<ErrorMessage name='username'>{msg => <div className='error'>{msg}</div>}</ErrorMessage>
</Col>
</Row>
<Row>
<Col xs={12}>
<label htmlFor='password'>Password:</label>
<Field type='password' name='password' />
<ErrorMessage name='password'>{msg => <div className='error'>{msg}</div>}</ErrorMessage>
</Col>
</Row>
<Row>
<Col xs={12}>
<label htmlFor='repeatPassword'>Repeat password:</label>
<Field type='password' name='repeatPassword' />
<ErrorMessage name='repeatPassword'>{msg => <div className='error'>{msg}</div>}</ErrorMessage>
</Col>
</Row>
</Col>
</Row>
<Row>
<Col xs={12}>
<button type='submit' disabled={isSubmitting}>
Create User
</button>
</Col>
</Row>
</Form>
)}
</Formik>
</Col>
</Row>
</React.Fragment>
);
}
Run Code Online (Sandbox Code Playgroud)
我首先看到的是,你已经剥离了标准的formik<Field />组件,直接改为<TextField />. 该<Field />组件实际上是一个特殊的组件,根据 fomik 文档,它“会自动将输入连接到 Formik。它使用 name 属性来与 Formik 状态匹配”。因此,我相信 formik 不再实际处理输入,而是这些不受控制的组件(没有由反应状态设置值的 html 组件)。随着 formik 不再处理输入,Yup 验证构建到 formik 中并通过 schema 属性使用将无法正常运行。
要解决此问题,您可以使用库(material UI 建议使用此库 - https://github.com/stackworx/formik-material-ui),也可以为 formik 制作自定义输入组件。这允许您将 s component 属性设置<Field />为正确连接材质 UI 与 formik 数据<Field />公开的组件。
const CustomTextInput = ({
field, // { name, value, onChange, onBlur }
form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
...props
}) => (
<div>
<TextField
error={_.get(touched, field.name) && _.get(errors, field.name) && true}
helperText={_.get(touched, field.name) && _.get(errors, field.name)}
{...field}
{...props}
/>
</div>
)
Run Code Online (Sandbox Code Playgroud)
然后在你的表格中你可以这样做
<Field
name="fieldName"
component={CustomTextInput}
label="You can use the Material UI props here to adjust the input"
/>
Run Code Online (Sandbox Code Playgroud)
您可以在 field 上的 formik 文档中找到有关此内容的示例和更多信息 - https://jaredpalmer.com/formik/docs/api/field
| 归档时间: |
|
| 查看次数: |
10812 次 |
| 最近记录: |