sdepold/sequelize — pull request #109 by hiddentao (2011-11-14 14:20:32+00:00)
Title: Add ability to supply custom validation methods for model fields

Hey Sascha, as mentioned in the previous issue (https://github.com/sdepold/sequelize/pull/108) it would be very useful to be able to supply your own data validation methods (beyond what node-validator) supplies when necessary. I've added changes + tests to enable this.

Here is how you would use custom validation. Each custom validation method recieves the field value to validate as its sole argument. It should throw an error to indicate a validation failure. For example:

User = sequelize.define('User', {
name: {
type: Sequelize.STRING,
validate: {
len: {
args: 9,
msg: "Need atleast 9 chars"
},
customFn1: function(val) {
# if name doesn't start with 'joe' then fail
if (val.substr(0,3) !== "joe")
throw new Error("name should start with 'joe'")
},
customFn2: function(val) {
# if name doesn't end in 'bloggs' then fail
if (val.substr(-6) !== "bloggs")
throw new Error("name should end with 'bloggs'")
}
}
}
});

You still invoke validation as you normally would, i.e.:

# build user
var user = User.build({
name : "test"
});

# validate
errors = user.validate();
# At this point errors will contain:
#
# { name : [
#	"Need atleast 9 chars"
#	"name should start with 'joe'"
#	"name should end with 'bloggs'"
# ] }
#