Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose validation: required : false, validate : regex, issues with empty values

I get this message from Mongoose validation:

'Validator failed for path phone with value ``'

That shouldn't happen since phone is not required.

Here's my model schema:

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

It seems that mongoose's validation fails when i use required: false and set validate property up. If I change it to:

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

Everything goes right, why is that? What am I doing wrong?

like image 593
Israel Cruz Avatar asked Feb 18 '14 01:02

Israel Cruz


2 Answers

I think your regex is failing validation on empty string which should in this case be valid since this field is not required. Why don't you try this regex:

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

This will match an empty string or 10 digits.

like image 52
Stepan Grigoryan Avatar answered Sep 30 '22 04:09

Stepan Grigoryan


You can simply check if the value entered exists (not null or undefined). If it exists, then test the regex:

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'}
);
like image 35
lwdthe1 Avatar answered Sep 30 '22 05:09

lwdthe1