gpt4 book ai didi

javascript - 如何更改 Yup/Formik 中的默认错误文本?

转载 作者:行者123 更新时间:2023-12-01 00:06:21 25 4
gpt4 key购买 nike

如果我单击电子邮件输入字段,该字段会显示“输入您的电子邮件”。这是我设定的。然而,在我打字的过程中,当验证检查没有完成时,它会说“输入有效的电子邮件”,这是默认的,不是我写的。

如果密码错误,由于我使用 .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 :包含字段错误消息的对象。

enter image description here enter image description here

最佳答案

我发现接受的答案是正确的,但在某些情况下可能不完整。将光标放入某个字段并按 Tab 键移出该字段可能会触发"is"“type error”。

默认的 Yup 类型错误是一个冗长且非用户友好的事情;)

我会将 AndreasT 的答案扩展为:

email:  Yup
.string()
.email('this will be displayed when email is wrong')
.required('this will be displayed when empty')
.typeError('A number is required')

Here is the article这让我想到了这个答案。

关于javascript - 如何更改 Yup/Formik 中的默认错误文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60356911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com