I'm trying to implement validation in my Sequelize models. The model is defined as follows
var model = sequelize.define('Model', {
from: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isEmail: true
}
}
}
Then I'm trying to build an instance and validate it:
var m = Model.build({ from: 'obviously not a email' });
var err = m.validate();
But if I do console.log(err)
, I get { fct: [Function] }
only. Defining a custom validator that throws an exception results in an unhandled exception.
How should I use validate()
properly?
Here is how to get your problem solved with Sequelize v2.0.0
:
var Sequelize = require("sequelize")
, sequelize = new Sequelize("sequelize_test", "root")
var Model = sequelize.define('Model', {
from: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isEmail: true
}
}
})
Model.sync().success(function() {
Model.build({ from: "foo@bar" }).validate().success(function(errors) {
console.log(errors)
})
})
This will result in:
{ from: [ 'Invalid email' ] }
Side note: You can also skip the validate
-call and just create the instance instead:
Model.sync().success(function() {
Model
.create({ from: "foo@bar" })
.success(function() {
console.log('ok')
})
.error(function(errors) {
console.log(errors)
})
})
The error method will receive the very same error object as in the previous code snippet.
Greetings, sdepold.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With