【问题标题】:Are unique custom validators names required?是否需要唯一的自定义验证器名称?
【发布时间】:2016-08-23 09:32:29
【问题描述】:

当我尝试创建新地址时,由于自定义验证器,验证每次都失败。当我将 companyExists 内容替换为“return true”时,它仍然失败。我发现一种解决方法是将其中一个文件中的自定义验证器重命名为其他名称,例如 companyExists2。似乎自定义验证器不能具有相同的名称。这是 Sails.js 的预期行为吗? Postman 返回 400 错误,说明验证失败,JSON 响应为:

"invalidAttributes": {
    "company": [
    {
        "rule": "companyExists",
        "message": "\"companyExists\" validation rule failed for input: 1\nSpecifically, it threw an error.  Details:\n undefined"
      }
    ]
 },

在 models/Address.js 我有:

module.exports = {
    attributes: {
        street: {
            type: 'string'
        },
        // More attributes
        company: {
            model: 'company',
            required: true,
            unique: true,
            companyExists: true
        }
    },
    types: {
        companyExists: function(companyID) {
            Company.findOne(companyID).exec(function(err, company) {
                if (err || !company) return false;
                return true;
            });
        }
    }
};

在 models/Company.js 我有:

module.exports = {
    attributes: {
        name: {
            type: 'string',
            required: true
        },
        // More attributes
        company: {
            model: 'company',
            required: true,
            unique: true,
            companyExists: true
       }
    },

    types: {
        companyExists: function(companyID) {
            Company.findOne(companyID, function (err, company) {
                if (err || !company) return false;
                return true;
            });
        }
    }
};

【问题讨论】:

    标签: sails.js


    【解决方案1】:

    自定义验证规则与内置规则合并。这使得它们可以在您的所有模型中访问。如果您多次需要相同的规则,则只需编写一次(无论在哪个模型中)。

    您还必须小心不要与现有规则发生冲突。你可以找到完整列表here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2017-03-02
      • 1970-01-01
      相关资源
      最近更新 更多