node.jsmongodbmongoosevalidator.js

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


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.


Solution

  • 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"
        }
      }