leepowelldev / mongoose-validator

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

Passing by validation without any effect #9

Closed eduardonunesp closed 10 years ago

eduardonunesp commented 10 years ago

The problem occurs when try save a post and the values are omitted for my validators, as following:

users_schame.js

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    validate = require('mongoose-validator').validate;

var nameValidate = [
    validate({message: 'Name cannot be null'}, 'notNull'),
    validate({message: 'Name invalid length'}, 'len', 5, 10)
];

var emailValidate = [
    validate({message: 'E-mail cannot be null'}, 'notNull'),
    validate({message: 'Invalid e-mail'}, 'isEmail')
];

var schema = {
    name: {type: String, validate: nameValidate},
    email: {type: String, validate: emailValidate},
    created: {type: Date, default: Date.now},
    updated: {type: Date, default: Date.now}
}

module.exports = mongoose.model('users', new Schema(schema));
module.exports.schema = schema;

So the request came with json data, but if the request in blank like {}, or if only one field is set like {"name":"Eddie"}, the other field (email) ins't tested.

user_resource.js

exports.addUser = function(req, res) {
    var user = JSON.parse(req.body.user);
    var userObj = new Users(user);
    userObj.save(function(err) {
        if (err) {            
            res.statusCode = 400;
            res.send(err);
        } else {
            //userObj.save()
            res.send(200);
        }
    });
};

Then i set to required: true in my schema, but the problem is cannot manipulate the error message with my validators.

leepowelldev commented 10 years ago

This is more of an issue with how Mongoose uses the validators. Validators will not be run by mongoose is no data exists - as you've discovered the only way or forcing them to run is to use required: true. If you are using the models error messages to update the view, then you may want to look at abstracting that out.

NetanelBasal commented 8 years ago

You found solution to this problem? how can i set custom messgae for required field?

leepowelldev commented 8 years ago

Why not use mongoose's built in required validator? - see the docs