2014-06-14 12 views
9

ho questo schema:Aggiungere più di un Convalida nella mangusta

var userSchema = new mongoose.Schema({ 
    name: {type: String,required: true,lowercase: true, trim: true}, 
    email: {type: String, required : true, validate: validateEmail }, 
    createdOn: { type: Date, default: Date.now }, 
    lastLogin: { type: Date, default: Date.now } 
}); 

e questo sono i miei validazione "regole"

var isNotTooShort = function(string) { 
    return string && string.length >= 5; 
}; 

var onlyLettersAllow = function(string) { 
    var myRegxp = /^[a-zA-Z]+$/i; 
    return myRegxp.test(string); 
}; 

Per convalidare il mio campo di nome Ho provato questo:

userSchema.path('name').validate(isNotTooShort, 'Is too short'); 
userSchema.path('name').validate(onlyLettersAllow, 'Only Letters'); 

e funziona. Posso aggiungere più convalide su un campo in Schema? Qualcosa di simile:

validate:[onlyLettersAllow,isNotTooShort] 

risposta

26

È possibile aggiungere più di una validazione in questo modo:

var manyValidators = [ 
    { validator: isNotTooShort, msg: 'Is too short' }, 
    { validator: onlyLettersAllow, msg: 'Only Letters' } 
]; 

var userSchema = new Schema({ 
    name: { type: String, validate: manyValidators }, 
    email: {type: String, required : true, validate: validateEmail }, 
    createdOn: { type: Date, default: Date.now }, 
    lastLogin: { type: Date, default: Date.now } 
}); 
+1

Docs qui: http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate – JohnnyHK

+0

super- risposte fantastiche ... – Fattie

Problemi correlati