paulducsantos
paulducsantos

Reputation: 289

Sequelize is allowing user to type "null" even with allowNull: false

I have a model for an Itinerary

var Itinerary = sequelize.define('Itinerary', {
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: true
    }
  }
})

This works for preventing empty inputs but if I type in "null" it still adds to my database. Reading the docs, it looks like it should prevent this from happening? Am I doing something wrong?

Upvotes: 0

Views: 458

Answers (1)

scottjustin5000
scottjustin5000

Reputation: 1346

Sequelize (and the db) is interpreting "null" as valid string.

itinerary.title ='null'; 

is different than:

itinerary.title = null;

you can add an additional validate method to your model to look for this string null if you'd like.

var Itinerary = sequelize.define('Itinerary', {
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    nullorEmpty: function() {
      if (!this.title || (this.title === 'null') {
        throw new Error('title must be set')
      }
    }
  }
})

Upvotes: 1

Related Questions