How can i validate type in mongoose custom validator

2.7k views Asked by At
key: {
    type: 'String',
    required: [true, 'Required'],
    trim: true
}

Whenever i validate it with custom validator, it converts to "String", which results in always valid type. Like "key" should only accept "String", if "Number" it should throw validation instead of casting it.

2

There are 2 answers

0
A_A On BEST ANSWER

(For those who are still stumbling across this question)

You can create a custom schema type for that, which doesn't allow casting. Then you can use this instead of String in your schemas (e.g. type: NoCastString).

function NoCastString(key, options) {
  mongoose.SchemaType.call(this, key, options, "NoCastString");
}
NoCastString.prototype = Object.create(mongoose.SchemaType.prototype);

NoCastString.prototype.cast = function(str) {
  if (typeof str !== "string") {
    throw new Error(`NoCastString: ${str} is not a string`);
  }
  return str;
};

mongoose.Schema.Types.NoCastString = NoCastString;
0
Gnana Sekar.J On

You can pass validation function to the validator object of the mongoose schema. See below the example Schema that have custom validation function to validate phone number schema.

    var userSchema = new Schema({
  phone: {
    type: String,
    validate: {
      validator: function(v) {
        return /\d{3}-\d{3}-\d{4}/.test(v);
      },
      message: '{VALUE} is not a valid phone number!'
    },
    required: [true, 'User phone number required']
  }
});

and this validation can be tested by asserting

    var User = db.model('user', userSchema);
var user = new User();
var error;

user.phone = '555.0123';
error = user.validateSync();
assert.equal(error.errors['phone'].message,
  '555.0123 is not a valid phone number!');

you can have your own Regular expression to match with whatever the pattern you want the string should be.