我如何验证猫鼬自定义验证器中的类型
How can i validate type in mongoose custom validator
key: {
type: 'String',
required: [true, 'Required'],
trim: true
}
每当我用自定义验证器验证它时,它都会转换为 "String",这
结果总是有效的类型。
像 "key" 应该只接受 "String",如果 "Number" 它应该抛出验证而不是转换它。
您可以将验证函数传递给 mongoose 模式的验证器对象。
请参阅下面的示例模式,该模式具有自定义验证功能以验证 phone 数字模式。
var userSchema = new Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: '{VALUE} is not a valid phone number!'
},
required: [true, 'User phone number required']
}
});
并且可以通过断言
来测试此验证
var User = db.model('user', userSchema);
var user = new User();
var error;
user.phone = '555.0123';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
'555.0123 is not a valid phone number!');
您可以拥有自己的正则表达式来匹配您想要的字符串的任何模式。
(对于那些仍然被这个问题绊倒的人)
您可以为此创建一个 custom schema type,它不允许转换。然后你可以在你的模式中使用它而不是字符串(例如 type: NoCastString
)。
function NoCastString(key, options) {
mongoose.SchemaType.call(this, key, options, "NoCastString");
}
NoCastString.prototype = Object.create(mongoose.SchemaType.prototype);
NoCastString.prototype.cast = function(str) {
if (typeof str !== "string") {
throw new Error(`NoCastString: ${str} is not a string`);
}
return str;
};
mongoose.Schema.Types.NoCastString = NoCastString;
key: {
type: 'String',
required: [true, 'Required'],
trim: true
}
每当我用自定义验证器验证它时,它都会转换为 "String",这 结果总是有效的类型。 像 "key" 应该只接受 "String",如果 "Number" 它应该抛出验证而不是转换它。
您可以将验证函数传递给 mongoose 模式的验证器对象。 请参阅下面的示例模式,该模式具有自定义验证功能以验证 phone 数字模式。
var userSchema = new Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{3}-\d{3}-\d{4}/.test(v);
},
message: '{VALUE} is not a valid phone number!'
},
required: [true, 'User phone number required']
}
});
并且可以通过断言
来测试此验证 var User = db.model('user', userSchema);
var user = new User();
var error;
user.phone = '555.0123';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
'555.0123 is not a valid phone number!');
您可以拥有自己的正则表达式来匹配您想要的字符串的任何模式。
(对于那些仍然被这个问题绊倒的人)
您可以为此创建一个 custom schema type,它不允许转换。然后你可以在你的模式中使用它而不是字符串(例如 type: NoCastString
)。
function NoCastString(key, options) {
mongoose.SchemaType.call(this, key, options, "NoCastString");
}
NoCastString.prototype = Object.create(mongoose.SchemaType.prototype);
NoCastString.prototype.cast = function(str) {
if (typeof str !== "string") {
throw new Error(`NoCastString: ${str} is not a string`);
}
return str;
};
mongoose.Schema.Types.NoCastString = NoCastString;