Handling Mongoose validation errors – where and how?

后端 未结 9 1671
孤城傲影
孤城傲影 2020-12-23 19:45

I\'m trying to decide how I want to handle validation errors in Mongoose.

Custom error messages using node-validator

I have defined my own validation rules

9条回答
  •  隐瞒了意图╮
    2020-12-23 20:07

    From Mongoose: https://github.com/leepowellcouk/mongoose-validator

    Error Messages Custom error messages are now back in 0.2.1 and can be set through the options object:

    validate({message: "String should be between 3 and 50 characters"}, 'len', 3, 50)


    How I implemented this:

    var emailValidator = [validate({message: "Email Address should be between 5 and 64 characters"},'len', 5, 64), validate({message: "Email Address is not correct"},'isEmail')];
    
    var XXXX = new Schema({
    email : {type: String, required: true, validate: emailValidator} }); 
    

    My front end deals with required, so I don't ever expect the mongoose "required" error to make it to the user, more of a back end safe guard.

提交回复
热议问题