16

How do I check that password and password_confirmation are the same ?

var Joi = require('joi'),
S = Joi.string().required().min(3).max(15);
exports.create = {
   payload: {
            username: S,
            email: Joi.string().email(),
            password: S,
            password_confirmation:  S
   }
}
Andrew Lavers
  • 8,023
  • 1
  • 33
  • 50
Whisher
  • 31,320
  • 32
  • 120
  • 201

2 Answers2

42

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

password: Joi.string().min(3).max(15).required(),
password_confirmation: Joi.any().valid(Joi.ref('password')).required().options({ language: { any: { allowOnly: 'must match password' } } })
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
  • 1
    onSubmit it is working fine but on `onChange` error is coming even both fields are same :( – Faisal Janjua Aug 04 '20 at 19:34
  • @FaisalJanjua I'm encountering the same issue, have you figured it out? – Amr Sep 27 '20 at 12:30
  • @Amr I was using Joi and had experience of more than 1 year, and I really disappointed due to many basic issues in this library. – Faisal Janjua Sep 28 '20 at 13:44
  • 2
    I started using `Yup` and my life became easier... more than you are thinking... I have created very dynamic form with very strange functionality but never encountered any limitation from this library, moreover it is same like Joi, so If you have background using `Joi` you can easily switch into `Yup` – Faisal Janjua Sep 28 '20 at 13:48
  • https://codechips.me/svelte-form-validation-with-yup/ this is brief example how to get started :) – Faisal Janjua Sep 28 '20 at 13:50
32

If you got "language" is not allowed error message. Oh, you've come to the right place.

Now, 2020 and with Joi v17.2.1 we can use Joi.any().equal() or Joi.any().valid() with Joi.ref() and custom message with messages():

password: Joi.string().min(3).max(15).required().label('Password'),
password_confirmation: Joi.any().equal(Joi.ref('password'))
    .required()
    .label('Confirm password')
    .messages({ 'any.only': '{{#label}} does not match' })

Or use options()

password: Joi.string().min(3).max(15).required().label('Password'),
password_confirmation: Joi.any().equal(Joi.ref('password'))
    .required()
    .label('Confirm password')
    .options({ messages: { 'any.only': '{{#label}} does not match'} })

Validate error will show ValidationError: "Confirm password" does not match if not match.
And show ValidationError: "Confirm password" is required if you have not pass password_confirmation.

Hope useful to someguys.

ThangLe
  • 878
  • 1
  • 8
  • 15