Mongoose schema validation: Error for empty string when validating a non-required field

5.1k Views Asked by At

I have a mongoose schema, like,

let Employee = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    trim: true,
    unique: true,
    validate: {
      validator: validator.isEmail,
      message: "{Value} is not valid"
    }
  },
  contactNum: {
    type: String,
    validate: {
      validator: validator.isMobilePhone,
      message: "{Value} is not valid"
    }
  },
  salary: {
    type: String
  }
});

I am validating for contactNum field to be a 'mobile phone number' but following error is occurring when I left contact number field empty -

message: "Employee validation failed: contactNum: {Value} is not valid", name: "ValidationError"

However, I don't want the contactNum field to be required.

2

There are 2 best solutions below

0
On BEST ANSWER

I am using validator.js module of npm for validation purposes in my mongoose schema and therefore I checked it's documentation here and with some more research I finally found the answer.

The schema can be updated to not validate for mobile phone number if value is empty, like -

contactNum: {
    type: String,
    required: false,
    validate: {
      validator: (value) => {

        // Check if value is empty then return true.
        if (value === "") {
          return true;
        }

        // If value is empty will not validate for mobile phone.
        return validator.isMobilePhone(value);
      },
      message: "{VALUE} is not valid"
    }
  }
3
On

you need to update your validator.isMobilePhone() into accepting null or empty values. And change your schema like this

 contactNum: {
    type: String,
    required:false,
    validate: {
      validator: validator.isMobilePhone,
      message: "{Value} is not valid"
    }
  }

by setting required to false you can achieve what you want.

change your validator js function like this

Validator.isMobilePhone('telephone', function(value, requirement, attribute) { // requirement parameter defaults to null
  if(value.toString()==""){return true;}
  return value.match(/^\d{3}-\d{3}-\d{4}$/);
}, 'The :attribute phone number is not in the format XXX-XXX-XXXX.');