Created
December 29, 2014 08:24
-
-
Save gadelkareem/17e714c69e57facc1271 to your computer and use it in GitHub Desktop.
Custom validation messages for sails js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//in api/models/User.js | |
function validationError(invalidAttributes, status, message) { | |
var WLValidationError = require('../../node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js'); | |
return new WLValidationError({ | |
invalidAttributes: invalidAttributes, | |
status: status, | |
message: message | |
} | |
); | |
} | |
var User = { | |
attributes: { | |
//... | |
}, | |
ownValidate:: function (values, update, cb) { | |
//example of not allowed param on update | |
//if it is an update then do not allow email param | |
if (update && values.email) { | |
return cb(validationError({ | |
email: [ | |
{ | |
message: 'Email is not allowed for updates.' | |
} | |
] | |
}, 400 /*status*/)); | |
} | |
sails.models['user'].findOne(values.email).exec(function (err, user) { | |
if (err) return cb(err); | |
if (user) { | |
return cb(validationError({ | |
email: [ | |
{ | |
value: values.email, | |
rule: 'E_UNIQUE' | |
/* unique validation message is left for the default one here */ | |
} | |
] | |
}, 409)); | |
} | |
}); | |
}, | |
beforeCreate: function (values, cb) { | |
return sails.models['user'].ownValidate(values, false, cb); | |
}, | |
beforeUpdate: function (values, cb) { | |
return sails.models['user'].ownValidate(values, true, cb); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment