2016-08-23 80 views
0

當我運行嘗試創建一個新的地址時,由於自定義驗證程序,驗證每次都失敗。當我用「返回true」替換companyExists內容時,它仍然失敗。我發現一個解決方法是將其中一個文件中的自定義驗證器重命名爲諸如companyExists2之類的其他文件。看起來自定義驗證器不能具有相同的名稱。這是Sails.js的預期行爲嗎?郵差返回400錯誤說驗證失敗的JSON響應:是否需要獨特的自定義驗證器名稱?

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

在模型/ 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; 
      }); 
     } 
    } 
}; 

在模型/ 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; 
      }); 
     } 
    } 
}; 

回答

0

自定義驗證規則與內置合併規則合併。這使得他們可以在所有模型中訪問。如果你多次需要相同的規則,你只需要寫一次(在哪個模型中無關緊要)。

您還必須小心,不要與現有規則相沖突。你可以找到完整的列表here