我需要使用Yup进行表单验证,以检查React App中的输入类型email1
,email2
,email3
,email4
和email5
。
经验法则很容易。检查那些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)
});
此方法的问题是,即使输入文本为空,它也会检测到重复电子邮件的错误。我该如何解决?有什么更好的方法可以实施吗?
谢谢
答案 0 :(得分:4)
您必须在此结构中使用
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
)});