【问题标题】:Validate email input field form element验证电子邮件输入字段表单元素
【发布时间】: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',
  });
}
  };

【问题讨论】:

标签: reactjs forms material-ui react-hook-form


【解决方案1】:

所以我发现你可以传递一个函数来验证属性来解决我的问题

<TextField
          name='recipientEmail'
          placeholder='Eg. recipient@email.com'
          inputRef={register({
            required: true,
            validate: {
              validEmail: (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, ''))) {
                    return false;
                  }
                }
              },
              emailLength: (value) => {
                let currentEmails = value
                  .split(',')
                  .filter((e) => e && e.trim());
                if (currentEmails.length > 10) {
                  return false;
                }
              },
            },
          })}
          error={errors.recipientEmail && true}
          fullWidth
        />

"validEmail" 验证电子邮件并 "emailLength" 验证电子邮件长度 谢谢你

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多