omer
omer

Reputation: 1440

Mongoose custom validator fails if non-required field is missing

I'm working with mongoose schemas, and wrote a custom validator for some non-required field. The validator work perfectly when the field is present, but fails if the field is missing (which is ok, since the field is not marked as 'required').

My questions are:

  1. Is this the correct behavior?
  2. How can I make it skip the validation if the field is missing?

Upvotes: 2

Views: 438

Answers (2)

omer
omer

Reputation: 1440

Found the problem: the mongoose schema contains the "default" property:

addr: { type: String, maxlength: [50, "max length for address"], validate: { validator: validators.validateAddress, message: "address is invalid" }, default: "" },

If this property appears, the object must have the 'addr' field, otherwise the validation fails.

Upvotes: 0

Simon Thiel
Simon Thiel

Reputation: 3285

You can use a custom validator as it is only called when the value exists.

See also: Mongoose validation: required : false, validate : regex, issues with empty values

Upvotes: 1

Related Questions