[英]How can i validate type in mongoose custom validator
key: {
type: 'String',
required: [true, 'Required'],
trim: true
}
Whenever i validate it with custom validator, it converts to "String", which results in always valid type. 每当我使用自定义验证器对其进行验证时,它将转换为“字符串”,从而导致始终有效的类型。 Like "key" should only accept "String", if "Number" it should throw validation instead of casting it.
像“键”只应接受“字符串”,如果“数字”应抛出验证而不是强制转换。
You can pass validation function to the validator object of the mongoose schema. 您可以将验证函数传递给猫鼬模式的验证器对象。 See below the example Schema that have custom validation function to validate phone number schema.
请参阅下面的示例架构,该示例架构具有用于验证电话号码架构的自定义验证功能。
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']
}
});
and this validation can be tested by asserting 可以通过断言来测试此验证
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!');
you can have your own Regular expression to match with whatever the pattern you want the string should be. 您可以拥有自己的正则表达式以匹配您希望字符串使用的任何模式。
(For those who are still stumbling across this question) (对于仍在此问题上绊脚石的人)
You can create a custom schema type for that, which doesn't allow casting. 您可以为此创建一个自定义架构类型 ,该类型不允许强制转换。 Then you can use this instead of String in your schemas (eg
type: NoCastString
). 然后,您可以在架构中使用它而不是String(例如,
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.