在 beforeCreate 挂钩中创建验证检查
Creating validation check in beforeCreate hook
我有一个 user
模型,我也想添加一些额外的验证。
我正在使用 beforeCreate
挂钩进行检查,但我在弄清楚之后要做什么时遇到了一些问题。
beforeCreate: function(values, callback) {
UserService.additionalCheck(values, function(err, success){
if(err){
return callback(err);
}
if(success === true){
callback();
}
else{
return callback('Did not validate');
}
});
}
问题是这会导致 500
状态和 Error (E_UNKNOWN) :: Encountered an unexpected error
。
我只想发送与 'invalidAttribute' 相同的响应,我该如何实现?
TLDR:如何进行我自己的无效属性检查和响应?
Sails 文档涵盖 custom validation on attributes 此处。下面的示例来自该文档。使用自定义验证意味着您不需要使用 beforeCreate 挂钩。
// api/models/foo
module.exports = {
types: {
is_point: function(geoLocation) {
return geoLocation.x && geoLocation.y
},
password: function(password) {
return password === this.passwordConfirmation;
}
},
attributes: {
firstName: {
type: 'string',
required: true,
minLength: 5,
maxLength: 15
},
location: {
//note, that the base type (json) still has to be defined
type: 'json',
is_point: true
},
password: {
type: 'string',
password: true
},
passwordConfirmation: {
type: 'string'
}
}
}
如果您还想要自定义验证消息,以及一些 Rails 如 findOrCreate
类型 class 方法,您可以使用 Sails Hook Validation 包。请注意,它需要 Sails 0.11.0+。
我有一个 user
模型,我也想添加一些额外的验证。
我正在使用 beforeCreate
挂钩进行检查,但我在弄清楚之后要做什么时遇到了一些问题。
beforeCreate: function(values, callback) {
UserService.additionalCheck(values, function(err, success){
if(err){
return callback(err);
}
if(success === true){
callback();
}
else{
return callback('Did not validate');
}
});
}
问题是这会导致 500
状态和 Error (E_UNKNOWN) :: Encountered an unexpected error
。
我只想发送与 'invalidAttribute' 相同的响应,我该如何实现?
TLDR:如何进行我自己的无效属性检查和响应?
Sails 文档涵盖 custom validation on attributes 此处。下面的示例来自该文档。使用自定义验证意味着您不需要使用 beforeCreate 挂钩。
// api/models/foo
module.exports = {
types: {
is_point: function(geoLocation) {
return geoLocation.x && geoLocation.y
},
password: function(password) {
return password === this.passwordConfirmation;
}
},
attributes: {
firstName: {
type: 'string',
required: true,
minLength: 5,
maxLength: 15
},
location: {
//note, that the base type (json) still has to be defined
type: 'json',
is_point: true
},
password: {
type: 'string',
password: true
},
passwordConfirmation: {
type: 'string'
}
}
}
如果您还想要自定义验证消息,以及一些 Rails 如 findOrCreate
类型 class 方法,您可以使用 Sails Hook Validation 包。请注意,它需要 Sails 0.11.0+。