Mandate check: required: false, validate: regex, problems with empty values

I get this message from Mongoose check:

'Failed to execute validator for empty phone with value ``' '

This should not be, since the phone is not required.

Here is my model diagram:

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

The mongoose check seems to fail when I use required: falseand set the validate property up. If I change it to:

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

Everything is going right, why? What am I doing wrong?

+3
source share
3 answers

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

: Mongoose ?

, , .

BonusTip:. , , , , , lodash , , , .

+2

, , , . :

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

10 .

+2

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

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

All Articles