标签:
自定义验证器
//确保值是something function validator(val){ return val == "something"; } new Schema({name:{type:String, validate: validator}}); //自定义错误信息 var custom =[validator, ‘{PATH} does not equal something‘]; new Schema({name:{type:String, validate: custome}}); //一次添加多个验证器 var many = [ {validator:validator, msg:‘uh oh‘}, {validator: anotherValidator, msg: ‘failed‘} ]; new Schema({name: {type:String, validate:many}); //or var schema = new Schema({name: ‘string‘}); schema.path(‘name‘).validate(validator, "{PATH} {VALUE}");
var toySchema = new Schema({ color: String, name: String }); var Toy = mongoose.model(‘Toy‘, toySchema); Toy.schema.path(‘color‘).validate(function (value) { return /blue|green|white|red|orange|periwinkle/i.test(value); }, ‘Invalid color‘); var toy = new Toy({ color: ‘grease‘}); toy.save(function (err) { // err is our ValidationError object // err.errors.color is a ValidatorError object console.log(err.errors.color.message) // prints ‘Validator "Invalid color" failed for path color with value `grease`‘ console.log(String(err.errors.color)) // prints ‘Validator "Invalid color" failed for path color with value `grease`‘ console.log(err.errors.color.type) // prints "Invalid color" console.log(err.errors.color.path) // prints "color" console.log(err.errors.color.value) // prints "grease" console.log(err.name) // prints "ValidationError" console.log(err.message) // prints "Validation failed" });
当验证发生错误的时候, document通用会有一个erros属性:
toy.errors.color.message == err.errors.color.message
标签:
原文地址:http://www.cnblogs.com/irocker/p/4332263.html