簡體   English   中英

我如何驗證貓鼬自定義驗證器中的類型

[英]How can i validate type in mongoose custom validator

key: {
    type: 'String',
    required: [true, 'Required'],
    trim: true
}

每當我使用自定義驗證器對其進行驗證時,它將轉換為“字符串”,從而導致始終有效的類型。 像“鍵”只應接受“字符串”,如果“數字”應拋出驗證而不是強制轉換。

您可以將驗證函數傳遞給貓鼬模式的驗證器對象。 請參閱下面的示例架構,該示例架構具有用於驗證電話號碼架構的自定義驗證功能。

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

可以通過斷言來測試此驗證

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

您可以擁有自己的正則表達式以匹配您希望字符串使用的任何模式。

(對於仍在此問題上絆腳石的人)

您可以為此創建一個自定義架構類型 ,該類型不允許強制轉換。 然后,您可以在架構中使用它而不是String(例如, 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM