Generalmente uso una funzione di supporto per tali cose. Ho appena preso in giro questo per essere un po 'più generale di quelli che uso. Questo tizio prenderà tutti i validatori "predefiniti" (obbligatori, min, max, ecc.) E renderà i loro messaggi un po 'più carini (secondo l'oggetto messages
di seguito) ed estrarrà solo il messaggio che hai passato nel tuo validatore per l'abitudine convalide.
function errorHelper(err, cb) {
//If it isn't a mongoose-validation error, just throw it.
if (err.name !== 'ValidationError') return cb(err);
var messages = {
'required': "%s is required.",
'min': "%s below minimum.",
'max': "%s above maximum.",
'enum': "%s not an allowed value."
};
//A validationerror can contain more than one error.
var errors = [];
//Loop over the errors object of the Validation Error
Object.keys(err.errors).forEach(function (field) {
var eObj = err.errors[field];
//If we don't have a message for `type`, just push the error through
if (!messages.hasOwnProperty(eObj.type)) errors.push(eObj.type);
//Otherwise, use util.format to format the message, and passing the path
else errors.push(require('util').format(messages[eObj.type], eObj.path));
});
return cb(errors);
}
E può essere utilizzato in questo modo (esprimere esempio router):
function (req, res, next) {
//generate `user` here
user.save(function (err) {
//If we have an error, call the helper, return, and pass it `next`
//to pass the "user-friendly" errors to
if (err) return errorHelper(err, next);
}
}
Prima:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ message: 'Validator "required" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'required' },
state:
{ message: 'Validator "enum" failed for path state',
name: 'ValidatorError',
path: 'state',
type: 'enum' },
email:
{ message: 'Validator "custom validator here" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'custom validator here' },
age:
{ message: 'Validator "min" failed for path age',
name: 'ValidatorError',
path: 'age',
type: 'min' } } }
Dopo:
[ 'username is required.',
'state not an allowed value.',
'custom validator here',
'age below minimum.' ]
Modifica: Snap, ho appena realizzato che si trattava di una domanda di CoffeeScript. Non essendo un tipo CoffeeScript, non vorrei davvero riscriverlo in CS. Potresti sempre richiederlo come file js
nel tuo CS?
C'è anche espresso validatore che funziona bene. – chovy