0

How can I compare password and password_confirmation, and if they don't match then I'll print "Passwords don't match" to the error message?

const userSchema = new Schema(
  {
    username: {type: String, required: [true, "Please enter a username"], unique: [true, "Username taken"]},
    password: {type: String, required: true, minLength: [8, "Minimum password lenth is 8"]},
    password_confirmation: {type: String}
  },
  { timestamps: true }
);
sulemani
  • 9
  • 1
  • Does this answer your question? [Validating password / confirm password with Mongoose schema](https://stackoverflow.com/questions/13982159/validating-password-confirm-password-with-mongoose-schema) – Ahmad Habib May 19 '21 at 13:07
  • No, the answer is probably outdated. @AhmadHabib – sulemani May 19 '21 at 13:16

1 Answers1

1

You can use validator in your schema. https://www.npmjs.com/package/validator

passwordConfirm: {
type: String,
required: [true, 'Please confirm your password'],
validate: {
  // this only works on CREATE and  SAVE!!!!
  validator: function (el) {
    return el === this.password;
  },
  message: 'Password and password confirmation do not match.',
},

}

Gesuchter
  • 541
  • 5
  • 13
Yuliia
  • 21
  • 2