使用Yup进行表单验证以检查输入值是否相等

时间:2019-11-13 07:55:06

标签: javascript reactjs validation yup

我需要使用Yup进行表单验证,以检查React App中的输入类型email1email2email3email4email5

经验法则很容易。检查那些emails的格式正确,并且不能具有相似的emails值。

我对Yup非常陌生。所以我要做的是:

const message = 'Duplicate emails not allowed';
const incorrect = 'Incorrect email format';

const Schema = Yup.object().shape({
  email1: Yup.string()
    .email(incorrect)
    .oneOf([Yup.ref('email2'), null], message)
    .oneOf([Yup.ref('email3'), null], message)
    .oneOf([Yup.ref('email4'), null], message)
    .oneOf([Yup.ref('email5'), null], message),
  email2: Yup.string()
    .email(incorrect)
    .oneOf([Yup.ref('email1'), null], message)
    .oneOf([Yup.ref('email3'), null], message) 
    .oneOf([Yup.ref('email4'), null], message)
    .oneOf([Yup.ref('email5'), null], message),
  email3: Yup.string()
    .email(incorrect)
    .oneOf([Yup.ref('email1'), null], message)
    .oneOf([Yup.ref('email2'), null], message)
    .oneOf([Yup.ref('email4'), null], message)
    .oneOf([Yup.ref('email5'), null], message),
  email4: Yup.string()
    .email(incorrect)
    .oneOf([Yup.ref('email1'), null], message)
    .oneOf([Yup.ref('email2'), null], message)
    .oneOf([Yup.ref('email3'), null], message)
    .oneOf([Yup.ref('email5'), null], message),
  email5: Yup.string()
    .email(incorrect)
    .oneOf([Yup.ref('email1'), null], message)
    .oneOf([Yup.ref('email2'), null], message)
    .oneOf([Yup.ref('email3'), null], message)
    .oneOf([Yup.ref('email4'), null], message)
});

此方法的问题是,即使输入文本为空,它也会检测到重复电子邮件的错误。我该如何解决?有什么更好的方法可以实施吗?

谢谢

1 个答案:

答案 0 :(得分:4)

使用notOneOf代替oneOf

您必须在此结构中使用


const ValidationSchema=Yup.object().shape({email1: Yup.string().email(this.incorrect)
  .notOneOf(
    [
      Yup.ref('email2'),
      Yup.ref('email3'),
      Yup.ref('email4'),
      Yup.ref('email5')
    ],
    this.message
  ),

email2: Yup.string()
  .email(this.incorrect)
  .notOneOf(
    [
      Yup.ref('email1'),
      Yup.ref('email3'),
      Yup.ref('email4'),
      Yup.ref('email5')
    ],
    this.message
  ),
email3: Yup.string()
  .email(this.incorrect)
  .notOneOf(
    [
      Yup.ref('email1'),
      Yup.ref('email2'),
      Yup.ref('email4'),
      Yup.ref('email5')
    ],
    this.message
  ),

email4: Yup.string()
  .email(this.incorrect)
  .notOneOf(
    [
      Yup.ref('email1'),
      Yup.ref('email2'),
      Yup.ref('email3'),
      Yup.ref('email5')
    ],
    this.message
  ),
email5: Yup.string()
  .email(this.incorrect)
  .notOneOf(
    [
      Yup.ref('email1'),
      Yup.ref('email2'),
      Yup.ref('email3'),
      Yup.ref('email4')
    ],
    this.message
  )});