Reputation: 18177
I have a user
model which I would like to add some additional validation too.
I am using the beforeCreate
hook to do my checks, but I am having some trouble figuring out what to do after that.
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');
}
});
}
The problem is that this results in a 500
status and Error (E_UNKNOWN) :: Encountered an unexpected error
.
All I want to do is send the same kind of response that you get when you have an 'invalidAttribute', how can I accomplish this?
TLDR: How can I make my own invalid attribute checks and responses?
Upvotes: 1
Views: 369
Reputation: 502
Sails documentation covers custom validation on attributes here. The example below pulls from that documentation. Using the custom validations would mean you don't need to use a beforeCreate hook.
// 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'
}
}
}
If you'd also like custom validation messaging, as well as a few Rails like findOrCreate
type class methods you can use the Sails Hook Validation package. Note that it requires Sails 0.11.0+.
Upvotes: 1