jht*_*ong 5 javascript sails.js
如何使用Sails JS中的object类型的属性验证模型?
我知道具有简单值(例如字符串)的属性是可以接受的,但是这对嵌套JSON有何作用?
如下:
{
name: 'John',
location: {
x: 23,
y: 15,
z: 50
}
}
Run Code Online (Sandbox Code Playgroud)
它会是这样的形式:
{
name: {
type: 'string',
required: true,
},
location: {
x: {
type: 'number',
required: true
},
y: {
type: 'number',
required: true
},
z: {
type: 'number',
required: true
}
}
}
Run Code Online (Sandbox Code Playgroud)
Waterline(Sails ORM)不直接支持嵌套模式.您可以使用自定义验证规则来验证属性:
module.exports = {
types: {
location: function(val) {
// Make sure that x, y and z are present and are numbers.
// This won't allow numeric strings, but you can adjust to fit your needs.
return (_.isNumber(val.x) && _.isNumber(val.y) && _.isNumber(val.z));
}
},
attributes: {
location: {
type: 'json',
required: true, // If you want the whole attribute to be required
location: true // Validate that the attribute has the schema you want
}
...more attributes...
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1618 次 |
| 最近记录: |