benui
benui

Reputation: 6808

Validating multiple Mongoose schema properties?

I'm trying to do the classic thing of making sure a user's username is not the same as their password, in Nodejs/Mongoose.

I was thinking it'd be good to use a seperate validation function, but I can't work out how to do it.

So far I've used the model code from Alex Young's Notepad tutorial. He creates a virtual password property which I've re-used.

I've got basic validation as follows:

function validatePresenceOf(value) {
    return value && value.length;
}

User = new Schema({
    'username': {
        type: String,
        validate: [
            validatePresenceOf, 'a username is required',
        ],
        index: { unique: true }
    },
});

How would I allow a validator to access other properties?

Upvotes: 7

Views: 4745

Answers (2)

Derek Hill
Derek Hill

Reputation: 6454

Using Mongoose 5, I could not get the accepted answer to work for me.

Instead, following the pre-validate middleware approach in this answer, using invalidate, this did the trick:

schema.pre('validate', function (next) {
  if (this.username === this.password) {
    this.invalidate('password', 'Password cannot equal username', this.password);
  }
  next();
});

Upvotes: 0

Logos
Logos

Reputation: 238

You can call additional properties of the schema via this.propertyToBeCalled.

schema.path('name').validate(function(v) {
    if (v === this.password) {
        return false;
    } else {
        return true;
    }
}, 'my error type');

Or something like that anyway.

Upvotes: 8

Related Questions