Password confirmation and password are equal but validation is still triggering JOI in React component

巧了我就是萌 提交于 2020-01-06 06:06:36

问题


I creating a register form and the problems accurs while try validating password confirmation. I am using the last version of JOI-Browser.

I tried the code below and the validation error was triggered even though password and password confirmation have the same values.

password: Joi.string()
      .min(5)
      .required(),
passwordConfirmation: Joi.ref("password")

Here is my state object:

password: "12345"
passwordConfirmation: "12345"
username: ""
errors: {…}
passwordConfirmation: "\"passwordConfirmation\" must be one of [ref:password]"

I passed several hours trying several approaches and reading the documentation, but still no luck, the validation is still triggering,

I have other validations in this form and they work fine.


回答1:


I don't think Joi.ref should be used that way.

I usually tend to do this way:

const passwordConfirmation = Joi.string()
  .required()
  .valid(Joi.ref('password'))
  .options({
    language: {
      any: {
        allowOnly: '!!Passwords do not match',
      }
    } 
  })

If you refer to the docs, you will see:

Note that references can only be used where explicitly supported such as in valid() or invalid() rules. If upwards (parents) references are needed, use object.assert().




回答2:


I find out what was happening. My code above was right, the problem was in my validate function.

Gabriele's Petrioli comment help me out. this is the function that cause me problems:

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;};

Has you can see i tried validate each property individually, so i can make the form mora dynamic.

This trigger the validation error because when i try to validate confirmPassword there was no value in password because i passed only the value the correspond to confirmaPassword, it also needed the password value to make the comparison.

Rookie mistake



来源:https://stackoverflow.com/questions/56779021/password-confirmation-and-password-are-equal-but-validation-is-still-triggering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!