我使用“ Formik”库实现表单
我有此代码:
import { useFormik } from 'formik';
import * as yup from 'yup';
import FInput from './FInput/FInput';
const Form = () => {
const {handleSubmit, values, handleChange} = useFormik({
initialValues: {
username: '',
email: '',
password: '',
confirm_password: '',
},
validationSchema: yup.object().shape( schema: {
username: yup.string() // the error here
.required('This field is required'),
email: yup.string()
.required('This field is required')
.email('This field is required'),
password: yup.string()
.required('This field is required')
.min(6, 'This password is too short')
.max(30, 'This passwors is too long'),
confirm_password: yup.string()
.oneOf([yup.ref(key:'password'), null])
.required('This field is required'),
}),
onSubmit: (formValues) => {
console.log('submit', formValues);
},
});
return (
<form className="fform" onSubmit={handleSubmit}>
<FInput
label="username"
id="username"
inputProps={{
name:'username',
value: values.username,
onChange: handleChange,
}}
/>
<FInput
label="email"
id="email"
inputProps={{
name:'email',
value: values.email,
onChange: handleChange,
type: 'email',
}}
/>
<FInput
label="password"
id="password"
inputProps={{
name:'password',
value: values.password,
onChange: handleChange,
type:'password',
}}
/>
<FInput
label="Confirm password"
id="confirm_password"
inputProps={{
name:'confirm_password',
value: values.confirm_password,
onChange: handleChange,
type:'password',
}}
/>
<button type="submit">Submit Form</button>
</form>
);
};
export default Form;
我有错误:
第18:25行:分析错误:意外的保留类型字符串
18 |用户名:yup.string()
顺便说一句,username
不会在文本编辑器中以彩色突出显示。
如何解决错误?我已经看了很多遍代码了,无法理解导致错误的原因。请帮助解决此问题。
答案 0 :(得分:1)
object.shape
API将其中包含字段的对象作为参数。
Formik的Yup定义必须为:
validationSchema: yup.object().shape({
username: yup.string()
.required('This field is required'),
email: yup.string()
.required('This field is required')
.email('This field is required'),
password: yup.string()
.required('This field is required')
.min(6, 'This password is too short')
.max(30, 'This passwors is too long'),
confirm_password: yup.string()
.oneOf([yup.ref(key:'password'), null])
.required('This field is required'),
})