Everything I’ve found indicates that an empty string can be matched in a regular expression by /^$/. However, that expression is not working in my Mongoose Validator for zipcode.
I want to set zipcode if one of two states is true – either it is empty or it is a valid, five digit number.
ZIP_REGEX: /^$|^[0-9]{5}$/
zip: {
type: Number,
validate: [ ZIP_REGEX, 'ValidationError']
},
This validator fails each time I attempt to store an empty string. The result is I can set valid zipcode, but never unset them. Is Mongoose also trying to verify that the empty string is a Number? Is the regular expression wrong?
Use a custom validation function for anything a bit unusual like this. Assuming you want to support both numbers and strings as input: