Tag Archives: ndoe

How to : Add custom validation to a Mongoose Model

I need to add a custom validation to my mongoose model before I save to my Mongo Database.

Answer –

  • Custom validation is declared by passing a validation function.


  • Note* Custom validation – method signature = validate(obj, [errorMsg])

var phoneValidator = [
   return /d{3}-d{3}-d{4}/.test(v); 
 "Please provide a valid phone number"

var customerSchema = new Schema(
   phone : 
     type: String, 
     validate: phoneValidator 

var Customer = mongoose.model('customer', customerSchema);