将几个参数传递给NodeJS验证函数
我有一个验证函数,用于检查模型中的内容长度。
let contentLengthchecker = (content) => {
if(!content){
return false;
}else{
if(content.length < 5 || content.length > 100){
return false;
}else{
return true;
}
}
};
所以,我把它作为验证器字段放在这样的模型架构上......
const titleValidators = [
{validator: contentLengthchecker, message: 'Title length must be between 6 to 30 characters'}
];
并将该数组放在模型的验证器字段中。
const adSchema = new Schema({
title: {type: String, required: true, validate: titleValidators},
description: {type: String, required: true, validate: descriptionValidators}
});
所以,现在我想让这个功能有点可重用。所以,我这样写
let contentLengthchecker = (content, minLength, maxLength) => {
if(!content){
return false;
}else{
if(content.length < minLength || content.length > maxLength){
return false;
}else{
return true;
}
}
};
但是,现在我正在努力将minLength和maxLength参数传递给它。我不知道将它们放在模型架构中的哪个位置。
那么,在哪里放置其他参数?
回答如下:const titleValidators = [{
validator: contentLengthchecker,
message: 'Title length must be between 6 to 30 characters',
minLength: 6,
maxLength: 30
}];
let contentLengthchecker = (content) => {
if(!content){
return false;
}else{
if(!this.minLength || !this.maxLength){
throw 'minLength or maxLength is not specified';
}
if(content.length < this.minLength || content.length > this.maxLength){
return false;
}else{
return true;
}
}
我认为这应该有效。