【发布时间】:2020-06-06 23:04:14
【问题描述】:
如果我单击电子邮件输入字段,该字段会显示“输入您的电子邮件”。这是我设置的。但是,在我打字的过程中,当验证检查未完成时,它会说“输入有效的电子邮件”,这是默认设置,不是我写的。
如果密码错误,由于我使用的是 .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"
)
});
这就是我的 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 },
errors,
touched,
handleChange,
isValid,
setFieldTouched
} = props;
const change = (name: string, e: { persist: () => void; }) => {
e.persist();
handleChange(e);
setFieldTouched(name, true, false);
};
return (
<form style={{ width: '100%' }} onSubmit={_ => alert('Submitted!')}>
<TextField
variant="outlined"
margin="normal"
id="email"
fullWidth
name="email"
helperText={touched.email ? errors.email : ""}
error={touched.email && Boolean(errors.email)}
label="Email"
value={email}
onChange={change.bind(null, "email")}
/>
<TextField
variant="outlined"
margin="normal"
fullWidth
id="password"
name="password"
helperText={touched.password ? errors.password : ""}
error={touched.password && Boolean(errors.password)}
label="Password"
type="password"
value={password}
onChange={change.bind(null, "password")}
/>
</Formik>
在 Formik props 中,errors : 一个包含字段错误信息的对象。
【问题讨论】:
标签: javascript reactjs typescript formik yup