Tag Archives: schema

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.

Example

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

var phoneValidator = [
 function(_value){ 
   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);