sdepold/sequelize — pull request #108 by hiddentao (2011-11-11 16:06:14+00:00)
Title: Add ability to validate models using the node-validator library

Added validation to models using node-validator (https://github.com/chriso/node-validator).

To validate your models first define the validation for each field. For example:

```
var User = sequelize.define 'User', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: {
len: {
args: 3,
msg: "Name must be atleast 3 characters in length"
}
}
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: {
len: {
args: [6, 128],
msg: "Email address must be between 6 and 128 characters in length"
},
isEmail: {
msg: "Email address must be valid"
}
}
},
password: {
type: Sequelize.STRING,
allowNull: false,
validate: {
len: {
args: 3
}
}
}
}
```

Any of the basic validation methods provided by the node-validation can be specified along with arguments, as shown above. The 'msg' key specifies the error message to return for a given validation if it fails. If this isn't provided then a default generic error message will be returned by the validation library.

To actually perform the validation, call the validate() method on your model instance once your model has been built. For example:

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

# validate
errors = user.validate();
if (errors)
# errors is an object with the following structure:
# { field name : [list of validation failure messages]
for (var prop in errors) {
if (errors.hasOwnProperty(prop))
console.log("Errors for field " + prop + ": ");
for (var i=0; i