Sit*_*thu 2 arrays postgresql validation node.js sequelize.js
我正在使用Node.js + PostgreSQL + Sequelize.js 2.0.2。我对电话字段有以下架构定义,它可以是字符串数组,但只允许数字:
var User = sequelize.define("User", {
....
....
/** Phone number
* Multiple numbers should be registered due to
*/
phone: {
type: Sequelize.ARRAY(Sequelize.STRING),
allowNull: false,
unique: true,
validate: {
isNumeric: true
}
},
....
....
});
Run Code Online (Sandbox Code Playgroud)
数字电话号码数组未通过验证。
输入:[ '9252522525', '9252525555' ]
错误:
{ [SequelizeValidationError: Validation error]
name: 'SequelizeValidationError',
message: 'Validation error',
errors:
[ { message: 'Validation isNumeric failed',
type: 'Validation error',
path: 'phone',
value: 'Validation isNumeric failed',
__raw: 'Validation isNumeric failed' } ] }
Run Code Online (Sandbox Code Playgroud)
但单值数组输入[ '9252522525' ]成功。是 Sequelize 的 bug 还是我错了?
我将验证器更改为is,但没有成功。
validate: {
is: ["^[0-9]+$", "i"]
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误。
{ [SequelizeValidationError: Validation error]
name: 'SequelizeValidationError',
message: 'Validation error',
errors:
[ { message: 'Validation is failed',
type: 'Validation error',
path: 'phone',
value: 'Validation is failed',
__raw: 'Validation is failed' } ] }
Run Code Online (Sandbox Code Playgroud)
根据Sequelize github repo Issue,所有验证器都适用于数组,而不是数组中的单个项目,作为最终用户,我似乎不清楚这一点。解决方法是定义自定义验证器:
phone: {
type: Sequelize.ARRAY(Sequelize.STRING),
allowNull: false,
unique: true,
validate: {
isValidPhoneNo: function(value) {
if (!value) return value;
var regexp = /^[0-9]+$/;
var values = (Array.isArray(value)) ? value : [value];
values.forEach(function(val) {
if (!regexp.test(val)) {
throw new Error("Number only is allowed.");
}
});
return value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4720 次 |
| 最近记录: |