来自Yup自定义验证器的消息返回未定义的路径和引用名称



我正在尝试为yup验证库编写一个自定义测试,用于测试两个字段是否相同的node/express应用程序,例如测试密码和确认密码字段是否匹配。逻辑正在工作,但是方法提供的消息不起作用。

自定义验证程序代码修改自:https://github.com/jquense/yup/issues/97#issuecomment-306547261

自定义验证器

yup.addMethod(yup.string, 'isMatch', function (ref, msg) {
return this.test({
name: 'isMatch',
message: msg || `${this.path} must be equal to ${this.reference}`,
params: {
reference: ref.path
},
test: function (value) {
return value === this.resolve(ref);
}
});
});

示例使用

const schema = yup.object().shape({
password: yup.string().min(8),
passwordConfirm: yup.string().isMatch(yup.ref('password'))
})
const payload = {
password: 'correctPassword',
passwordConfirm: 'incorrectPassword'
}
schema.validate(payload)

从逻辑角度来看,上述方法如预期的那样工作。然而,在返回的错误消息中,this.paththis.reference的值都是undefined(即undefined must be equal to undefined(。它应该读成passwordConfirm must be equal to password

我必须在pathreference之前添加this.,否则节点将崩溃,并返回一个ReferenceError,即path/reference is not defined

您不需要编写自定义验证函数来检查两个字段是否匹配,您可以使用内置的验证器.oneOf

将一组值列入白名单。添加的值将自动删除从任何黑名单中删除。${values}插值可以在消息参数中使用。

请注意,即使未定义,undefined也不会使该验证器失败未包含在arrayOfValues中。如果您不希望未定义为有效值,可以使用mixed.required.

请参阅此处ref:oneOf(arrayOfValues:Array,message?:string| function(:架构别名:等于

因此,您可以如下重写您的模式(我在密码字段中也添加了required(:

const schema = yup.object().shape({
password: yup.string().min(8).required('Required!'),
passwordConfirm: yup.string().oneOf([Yup.ref('password')], 'Password must be the same!').required('Required!')
})

最新更新