Mongoose验证:必需:false,验证:正则表达式,空值问题

时间:2014-02-18 01:32:38

标签: regex node.js mongodb validation mongoose

我从Mongoose验证中收到此消息:

'确认者因路径电话失败而值为'''

这不应该发生,因为不需要电话。

这是我的模型架构:

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'}
);

当我使用required: false并设置validate属性时,似乎mongoose的验证失败了。 如果我将其更改为:

phone    : { type: String, required: false},

一切顺利,为什么? 我做错了什么?

3 个答案:

答案 0 :(得分:3)

我认为你的正则表达式对空字符串的验证失败,在这种情况下应该是有效的,因为这个字段不是必需的。你为什么不试试这个正则表达式:

/^$|^\d{10}$/ 

这将匹配空字符串或10位数字。

答案 1 :(得分:2)

您可以尝试使用自定义验证程序,因为它们仅在给定密钥存在值时触发,因为自定义验证的密钥选择是通过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');

看一下这个问题:Why Mongoose doesn't validate empty document?

如果验证失败,这也将有效地防止文档持久保存到数据库,除非您相应地处理错误。

BonusTip: 尝试以简单的方式接近自定义验证,例如尽可能避免使用循环,并避免使用lodash或underscore等库我的经验我已经看到,在处理大量交易时,这些可能会产生很大的性能成本。

答案 2 :(得分:0)

您只需检查输入的值是否存在(非空或未定义)。如果存在,则测试正则表达式:

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 == null || v.trim().length < 1) || re.test(v)
                     },
                     message: 'Provided phone number is invalid.'
                 }
    },
    password : { type: String },
    added    : { type: Date,    default: Date.now },
},
{collection : 'users'}
);
相关问题