Isr*_*ruz 5 regex validation mongoose mongodb node.js
我从猫鼬验证中收到以下消息:
'验证程序无法验证路径电话中的值``'
由于不需要电话,因此不应该发生这种情况。
这是我的模型架构:
var user = new Schema(
{
_id : { type: String, required: true },
name : { type: String, required: true},
phone : { type: String, required: false, validate: /^\d{10}$/ },
password : { type: String },
added : { type: Date, default: Date.now },
},
{collection : 'users'}
);
Run Code Online (Sandbox Code Playgroud)
当我使用required: false并设置validate属性时,似乎猫鼬的验证失败。如果我将其更改为:
phone : { type: String, required: false},
Run Code Online (Sandbox Code Playgroud)
一切正常,为什么呢?我究竟做错了什么?
lwd*_*he1 11
您可以简单地检查输入的值是否存在(不为空或未定义)。如果存在,则测试正则表达式:
var user = new Schema(
{
_id : { type: String, required: true },
name : { type: String, required: true},
phone : { type: String,/*not required by default**/
validate: {
validator: function(v) {
var re = /^\d{10}$/;
return (!v || !v.trim().length) || re.test(v)
},
message: 'Provided phone number is invalid.'
}
},
password : { type: String },
added : { type: Date, default: Date.now },
},
{collection : 'users'}
);
Run Code Online (Sandbox Code Playgroud)
我认为您的正则表达式未能对空字符串进行验证,在这种情况下应该是有效的,因为不需要此字段。你为什么不试试这个正则表达式:
/^$|^\d{10}$/
Run Code Online (Sandbox Code Playgroud)
这将匹配一个空字符串或 10 位数字。
小智 4
您可以尝试使用自定义验证器,因为它们仅在给定键上有值时才会触发,因为自定义验证的键选择是通过以下方式完成的path():
var user = new Schema({
// ...
phone : { type: String }, // using default - required:false
// ...
});
// Custom validation
user.path('phone').validate(function (value) {
// Your validation code here, should return bool
}, 'Some error message');
Run Code Online (Sandbox Code Playgroud)
看看这个问题:Why Mongoose does not validateempty document?
如果验证失败,这也将有效防止文档被持久化到数据库,除非您相应地处理错误。
BonusTip: 尝试以简单的方式处理自定义验证,例如,尽可能避免循环,并避免使用像 lodash 或 underscore 这样的库,因为根据我的经验,我发现这些库在处理大量事务时可能会产生显着的性能成本。