Password confirmation and password are equal but v

2020-05-08 07:25发布

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.

2条回答
叼着烟拽天下
2楼-- · 2020-05-08 08:06

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().

查看更多
Rolldiameter
3楼-- · 2020-05-08 08:11

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

查看更多
登录 后发表回答