3

In my Node application I use @hapi.Joi package for validations. I have the following code.

export function validateUser(user) {
  const schema = Joi.object({
    firstName: Joi.string().min(1).max(20).required(),
    lastName: Joi.string().min(1).max(20).required(),
    email: Joi.string().email().max(50).required(),
    mobile: Joi.string().min(8).max(12).required(),
    password: Joi.string().min(8).max(16).required(),
    confirmPassword: Joi.ref('password'),
  });

  return schema.validate(user);
}

But this doesn't check if the confirmPassword is required. I tried Joi.ref('password').required(). But it gives me an error. How can I solve this??

Shashika Virajh
  • 8,497
  • 17
  • 59
  • 103
  • `gives me an error` what error you are getting? – Chetan Oct 03 '19 at 11:15
  • You should check if password and confirm password are same or not. So if confirm password is not entered that means it's not same as password. – Chetan Oct 03 '19 at 11:17
  • Please check this reference [reference](https://stackoverflow.com/a/29829152/9116995) – Sudhakar Oct 03 '19 at 11:23
  • Possible duplicate of [Validate two properties are equal](https://stackoverflow.com/questions/57708043/validate-two-properties-are-equal) – a1300 Oct 04 '19 at 10:30

2 Answers2

8

For future reference

password: Joi.string().required(),    
confirmPassword:Joi.string().required().valid(Joi.ref('password')),
adjoke
  • 149
  • 2
  • 11
0

You can use Joi.any().valid() with Joi.ref():

confirmPassword: Joi.any().valid(Joi.ref('password')).required().options({ language: { any: { allowOnly: 'must match password' } } })
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43