Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a field required in Sequelize?

Let's say I want to make the firstname field required in sequelize, in mongoose I can just say required: true on that field but how do I do that in Sequelize?

like image 357
Daksh Miglani Avatar asked Jul 30 '17 10:07

Daksh Miglani


2 Answers

If you're using Sequelize, the equivalent of required: true on mongoose is just allowNull: false. You'd write something along these lines:

const YourTable = sequelize.define('your_table', {
  firstname: {
    type: Sequelize.STRING,

    // This will require the firstname be present
    allowNull: false,

    // If you want to also have a length restriction, add the next line
    len: [2,50], // only allow values with length between 2 and 50
       // That is 'Al' will be accepted and so will 'Rigoberto Fernando Luis María'. 
       // But '' or 'J' won't be good enough

     // If you use sequelize transforms, this will remove spaces on both ends
     // of the string also
     trim: true,
  },
  // All the other fields (columns)
});

References:

  • SequelizeJS models definition
  • Sequelize transforms
like image 171
joanolo Avatar answered Oct 15 '22 07:10

joanolo


To responde to Dmitry question: you can define a custom validation error under the field definition :

foo: {
  type: Sequelize.STRING,
  allowNull: false,
  validate: {
    notNull: { msg: "foo is required" },
  },
}

more info here

like image 36
Laurynas Ragauskas Avatar answered Oct 15 '22 07:10

Laurynas Ragauskas