Reputation: 1440
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:
Upvotes: 2
Views: 438
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
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