【发布时间】:2022-01-07 20:42:24
【问题描述】:
可以使用 react-hook-form 验证由逗号分隔的多封电子邮件。 所以我有一个 material-ui 文本字段,它使用 react-hook-form 进行验证..
初始输入字段接受一封电子邮件,并由 react-hook-form 验证。 目前我希望用户能够输入以逗号分隔的多封电子邮件,并验证每一封电子邮件。 目前我能够做的是在用户点击提交时进行验证,但是,我希望能够在用户输入电子邮件时进行验证。
<TextField
onChange={(e) => {
validateRecipientEmail(e.target.value);
}}
name='recipientEmail'
placeholder='sender@email.com'
fullWidth
inputRef={register({
required: true,
})}
error={errors.recipientEmail && true}
/>
{errors.recipientEmail && (
<Typography variant='caption' className={Type.textError}>
Invalid email address
</Typography>
)}
我找到了一种通过使用 onChange 事件侦听器进行验证来实现期望目标的方法。 但是在进行验证并在屏幕上填充错误之后。输入框不聚焦时,错误消失。
以下是我的验证
const validateRecipientEmail = (value) => {
let currentEmails = value.split(',').filter((e) => e && e.trim());
let regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+$/i;
for (let i = 0; i < currentEmails.length; i++) {
if (!regex.test(currentEmails[i].replace(/\s/g, ''))) {
setrecipientEmailErrorMessage(
`Enter valid Email(s) seperated by comma (,)`
);
setError('recipientEmail', {
type: 'manual',
});
}
}
if (currentEmails.length > 10) {
setrecipientEmailErrorMessage(`Emails should not be more than 10`);
setError('recipientEmail', {
type: 'manual',
});
}
};
【问题讨论】:
-
你检查过
helperText和FormHelperTextmui.com/components/text-fields/#helper-textmui.com/components/text-fields/#components -
谢谢,但我找到了一个有用的解决方案
标签: reactjs forms material-ui react-hook-form