Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add more than one validate in mongoose

I have this Schema:

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 }
});

and this are my validation "rules"

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

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

To validate my name field I tried this:

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

and it works. Can I add multiple validation on a field in Schema? Something like:

validate:[onlyLettersAllow,isNotTooShort]
like image 277
Barno Avatar asked Jun 14 '14 10:06

Barno


People also ask

How do I validate mongoose?

Mongoose registers validation as a pre('save') hook on every schema by default. You can disable automatic validation before save by setting the validateBeforeSave option. You can manually run validation using doc. validate(callback) or doc.

What is Mongoose unique validator?

mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.

What is __ V in MongoDB?

The __v field is called the version key. It describes the internal revision of a document.

Which of the following is a built-in Mongoose validator?

Mongoose provides several built-in validators such as required, minlength, maxlength, min, and max. These built-in validators are very useful and simple to configure.


1 Answers

You can add more than one validation like this:

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 }
});
like image 180
Christian P Avatar answered Sep 20 '22 09:09

Christian P