[英]How to create a conditional validator with mongoose validators
我目前有两个验证器与我的 Mongoose 架构一起运行,但是,如果数字字符串中是否存在连字符,我想始终根据条件执行我想要执行的第一个和第二个验证器。 我将如何 go 这样做?
这是我的问题代码:
const manyValidators = [
{ validator: function(number) {
const numberLength = number.length
return ((numberLength >= 9 && number.includes('-') === true) || (numberLength >= 8 && number.includes('-') === false ))
},
message: "You must have at least 8 characters if you do not have a hyphen but 9 characters if you do."
},
{ validator: function(number) {
return (number.indexOf('-') === -1 && ((number.indexOf('-') === 2 || number.indexOf('-') === 3)))
},
message: "There should be at least 2 or 3 characters before the hyphen"
}
]
const personSchema = new mongoose.Schema({
id: String,
name: {
type: String,
minlength: [3, "Names must be of 3 characters minimum."],
required: true
},
number: {
type: String,
validate: manyValidators,
required: true
}
})
第一个验证器由“如果没有连字符,则必须至少有 8 个字符,如果有,则必须至少有 9 个字符。 ”字符串组成,第二个是连字符验证器。
我太盲目了,我意识到验证器本身就是函数,所以我在有问题的return
语句之前添加了一个if
语句,以通过indexOf
确认是否存在连字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.