Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get Sequelize validation working

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?

like image 589
mrvn Avatar asked Jun 22 '13 16:06

mrvn


1 Answers

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.

like image 131
sdepold Avatar answered Oct 26 '22 06:10

sdepold