[英]Errors when trying to validate password confirmation in React form with Joi
[英]Password confirmation and password are equal but validation is still triggering JOI in React component
我创建了一个注册表,在尝试验证密码确认时出现问题。 我使用的是最新版本的 JOI-Browser。
我尝试了下面的代码,即使密码和密码确认具有相同的值,也触发了验证错误。
password: Joi.string()
.min(5)
.required(),
passwordConfirmation: Joi.ref("password")
这是我的状态对象:
password: "12345"
passwordConfirmation: "12345"
username: ""
errors: {…}
passwordConfirmation: "\"passwordConfirmation\" must be one of [ref:password]"
我花了几个小时尝试了几种方法并阅读了文档,但仍然没有运气,验证仍在触发,
我有这种形式的其他验证,它们工作正常。
我不认为Joi.ref
应该这样使用。
我通常倾向于这样做:
const passwordConfirmation = Joi.string()
.required()
.valid(Joi.ref('password'))
.options({
language: {
any: {
allowOnly: '!!Passwords do not match',
}
}
})
如果您参考docs ,您将看到:
请注意,引用只能在明确支持的情况下使用,例如在 valid() 或 invalid() 规则中。 如果需要向上(父)引用,请使用 object.assert()。
我知道发生了什么。 我上面的代码是正确的,问题出在我的验证函数中。
Gabriele 的 Petrioli 评论帮助了我。 这是导致我出现问题的功能:
validateProperty = ({ name: propertyName, value }) => {
const obj = { [propertyName]: value };
const schema = { [propertyName]: this.schema[propertyName] };
const { error } = Joi.validate(obj, schema);
return error ? error.details[0].message : null;};
您是否可以看到我尝试单独验证每个属性,以便我可以使表单 mora 动态化。
这会触发验证错误,因为当我尝试验证 confirmPassword 时,密码中没有值,因为我只传递了与 confirmaPassword 对应的值,它还需要密码值来进行比较。
菜鸟失误
如果有人遇到过类似的问题,这是我使用的解决方案:
validateProperty = (input) => {
let obj = { [input.name]: input.value };
let schema = { [input.name]: this.schema[input.name] };
if (input.name.endsWith("_confirm")) {
const dependentInput = input.name.substring(
0,
input.name.indexOf("_confirm")
);
obj[dependentInput] = this.state.data[dependentInput];
schema[dependentInput] = this.schema[dependentInput];
}
const { error } = Joi.validate(obj, schema);
return error ? error.details[0].message : null;
};
就我而言,我已经寻找_confirm
因为我的字段名称为password
和password_confirm
。 您需要根据您的要求在此处进行更改。
主要逻辑,您只需要在验证password_confirm
时添加password
value
和schema
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.