gpt4 book ai didi

sails.js - 针对数据库的sails js模型验证

转载 作者:行者123 更新时间:2023-12-01 08:55:40 30 4
gpt4 key购买 nike

我正在编写一个自定义验证规则来检查传递给我的 create 函数的“category_id”是否有效。

types: {
isValidCategoryId: function(id){
return Category.findOne({id: id}).exec(function(err, user){
if(err || !user)
return false;
else{
return true;
}
});
}
},


attributes: {
category_id : { isValidCategoryId: true, required: true, type: 'string' },
}

我知道我的自定义验证函数应该返回 true,但在异步上下文中,这可能不起作用,例如检查 DB 中的值。

我应该如何编写自定义验证函数以使其正常运行?

最佳答案

我尝试了particlebanana 的解决方案。它没有用,但至少它为我指明了正确的方向。

根据文档:

Validation rules may be defined as simple values or functions (both sync and async) that return the value to test against.

因此,一种简单的方法是:

attributes: {
category_id : {
required: true,
type: 'string',
'true': function(cb) {
Category.findOne({id: this.category_id}).exec(function(err, category){
return cb(!err && category);
});
}
}
}

如您所见,我在这里只使用“真实”验证器,但您当然可以编写自己的验证器来计算出一些更高级的逻辑。这里的关键是您的自定义验证器 不是异步的,但您的验证规则 可以是。是的,术语很困惑。

这是另一个使用自定义验证器的示例:

attributes: {
author: {
required: true,
type: 'string',
canPost: function(cb) {
Author.findOne(this.author).exec(function(err, author) {
return cb(author);
});
}
}
},
types: {
canPost: function(id, author) {
return author && author.canPost();
}
}

希望这是有道理的。如果没有,See the docs .

关于sails.js - 针对数据库的sails js模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27835101/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com