Barno
Barno

Reputation: 3331

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]

Upvotes: 18

Views: 7481

Answers (2)

answer:

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

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

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

another example : You can add more than one validation in mongoose like tags and use mongoose default validation like the name:

const Course = mongoose.model('Course', mongoose.Schema({
  name: {
    minLength: 5,
    maxLength: 50,
    type: String,
    required: true,
  },
  tags: {
    type: Array,
    required: true,
    validate: [
      {
        validator: function (v) {
            return v && v.length > 0
          },
          message: 'tags is required ...'
        },
        {
          validator: function (v) {
            return v && v.length < 2
          },
          message: 'tags are too much ...'
      }
    ]
  },
  date: { 
    type: Date,
    default: Date.now
  }
}))

Upvotes: 0

Christian P
Christian P

Reputation: 12240

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

Upvotes: 48

Related Questions