leepowelldev / mongoose-validator

Validators for mongoose models utilising validator.js
MIT License
379 stars 43 forks source link

Custom messages are not being passed to the errors array #33

Closed waleedq closed 8 years ago

waleedq commented 8 years ago

Hello,

custom messages set in the validate() function are not passed to the errors array, i only get the "Failed to validate path" message which is the default messages i guess

leepowelldev commented 8 years ago

Have you got a code sample I can see?

waleedq commented 8 years ago

`var emailValidator = [ validate({validator: 'isLength', arguments: [6, 50], message: "Email Address should be between 6 and 64 characters"}), validate({validator: 'isEmail', message: "Email Address is not correct"}) ];

var UserSchema = new Schema({ name: {type: String, required: true, validate: nameValidator}, }); ` The provided custom message in emailValidator is not being passed to the errors array.

wuffo commented 8 years ago

Yep, here too. Neither the message nor the httpStatus are being added to the error object.

leepowelldev commented 8 years ago

@wuffo httpStatus isn't automatically applied, you need to define it in your validator. It it then added to the properties object. So, for example, if your path is called name, you would find this at [error instance].errors.name.properties.httpStatus.

leepowelldev commented 8 years ago

@waleedq / @wuffo - I cannot replicate the problem of the custom message not being set. Running the tests shows it as working. The example you provided might be wrong though. You define an emailValidator, however you're validating against a nameValidator.

wuffo commented 8 years ago

Here's mine:

var usernameValidator = [
  validate({
    validator: 'isLength',
    arguments: [3, 25],
    message: 'wrong length'
  }),
  validate({
    validator: 'isAlphanumeric',
    message: 'bad characters'
  })
]
var emailValidator = [
  validate({
    validator: 'isEmail',
    message: 'email not valid'
  })
]

var UserSchema = new Schema({
  name: {
    first: {
      type: String,
      trim: true
    },
    last: {
      type: String,
      trim: true
    }
  },
  username: {
    type: String,
    trim: true,
    required: true,
    validate: usernameValidator,
    lowercase: true,
    unique: true
  },
  email: {
    type: String,
    trim: true,
    required: true,
    validate: emailValidator,
    lowercase: true,
    unique: true
  },
  hashed_password: {
    type: String,
    trim: true,
    required: true
  },
  profile_image: {
    type: String,
    trim: true,
    default: 'default'
  },
  join_date: {
    type: Date,
    required: true
  }
});
wuffo commented 8 years ago

Registration with any invalid data gets the response:

{
  "code": "InvalidContent",
  "message": ""
}
leepowelldev commented 8 years ago
var usernameValidator = [
  validate({
    validator: 'isLength',
    arguments: [3, 25],
    message: 'wrong length'
  }),
  validate({
    validator: 'isAlphanumeric',
    message: 'bad characters'
  })
]

var emailValidator = [
  validate({
    validator: 'isEmail',
    message: 'email not valid'
  })
]

var schema = new Schema({
  name: {
    first: {
      type: String,
      trim: true
    },
    last: {
      type: String,
      trim: true
    }
  },
  username: {
    type: String,
    trim: true,
    required: true,
    validate: usernameValidator,
    lowercase: true,
    unique: true
  },
  email: {
    type: String,
    trim: true,
    required: true,
    validate: emailValidator,
    lowercase: true,
    unique: true
  },
  hashed_password: {
    type: String,
    trim: true,
    required: true
  },
  profile_image: {
    type: String,
    trim: true,
    default: 'default'
  },
  join_date: {
    type: Date,
    required: true
  }
});

  var Person = mongoose.model('Person', schema, 'test.people');

  Person.create({
    join_date: Date.now(),
    hashed_password: '123456abc',
    email: 'foo',              // should fail here ... 
    username: '%bar$'  // ... and should fail here
  }, function(err, doc) {
    console.dir(err)
    if (err) return err;
    // ... everything worked as expected
  });

And this is the result I get

message: 'Person validation failed',
  name: 'ValidationError',
  errors: 
   { username: 
      { [ValidatorError: bad characters]
        properties: [Object],
        stack: // ...,
        message: 'bad characters',
        name: 'ValidatorError',
        kind: 'user defined',
        path: 'username',
        value: 'bar$%' },
     email: 
      { [ValidatorError: email not valid]
        properties: [Object],
        stack: // ...,
        message: 'email not valid',
        name: 'ValidatorError',
        kind: 'user defined',
        path: 'email',
        value: 'foo' } } }

This is what I would expect to see. I can only think there is something else in your application that is contributing towards your issue.

wuffo commented 8 years ago

Yes, I'll dig deeper. Thanks for testing.

ghost commented 8 years ago

Hello, I have the same issue in my local environment, I tested the code here (https://tonicdev.com/npm/mongoose-validator) and it's works!, the same code don't work in my machine :s, Not know what else to try.

Here is a basic example of the code:

var mongoose = require('mongoose');
var validate = require('mongoose-validator');

var nameValidator = [
        validate({
            validator: 'isLength',
            arguments: [3, 50],
            message: 'Name should be between {ARGS[0]} and {ARGS[1]} characters'
        }),
        validate({
            validator: 'isAlphanumeric',
            passIfEmpty: true,
            message: 'Name should contain alpha-numeric characters only'
        })
    ];

    var userSchema = new mongoose.Schema({
        name: {type: String, required: true, validate: nameValidator}
    });

    var User = mongoose.model('User', userSchema);
    var TestUser = new User({name: '_0'});

    TestUser.save(function (err) {
        if (err) {
            console.log(err);
        }
    });

And here is the logued error:

{ [ValidationError: Validation failed]
  message: 'Validation failed',
  name: 'ValidationError',
  errors: 
   { name: 
      { [ValidatorError: Validator failed for path `name` with value `_0`]
        message: 'Validator failed for path `name` with value `_0`',
        name: 'ValidatorError',
        path: 'name',
        type: 'user defined',
        value: '_0' } } }
leepowelldev commented 8 years ago

Odd, like you say in TonicDev it works as expected. Are you using the latest version of both mongoose and mongoose-validator?

ghost commented 8 years ago

This are the versions that I am using:

(package.json) "mongoose": "^3.8.39", "mongoose-validator": "^1.2.4",

leepowelldev commented 8 years ago

That's quite an old version of mongoose I think - try updating to the latest version and see if that helps.

ghost commented 8 years ago

Great! it's works! I thought that I had the correct version of mongoose, but yes I had an old version installed :s Now: 4.4.7 Thanks!!

leepowelldev commented 8 years ago

:thumbsup: