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?
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:
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
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