简体   繁体   中英

How can i validate type in mongoose custom validator

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.

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.

(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 (eg 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM