How to validate values passed into Sequelize models

Sequelize provides a validate option that you can use to validate the attribute values passed into your models.

Suppose you have a Users table with two columns: firstName and email.

When defining the model for the table, you can pass the validate option to any of your attributes that requires validation.

To validate the email field, you can use the provided isEmail validator as follows:

const User = sequelize.define(

 “User”,

 {

  firstName: Sequelize.STRING,

  email: {

   type: Sequelize.STRING,

   validate: { isEmail: true },

  },

 },

 { timestamps: false }

);

By adding the isEmail validation, Sequelize will throw an error when the email value you pass fails the validation check.

For example, when inserting a new row using the create() method as follows:

const response = await User.create({

 firstName: “Jack”,

 email: “jack”, // Error: Validation isEmail on email failed

});

Sequelize provides many built-in validators that you can use in your validate option.We can also create a custom validator by passing a function.

const User = sequelize.define(

 “User”,

 {

  firstName: Sequelize.STRING,

  email: Sequelize.STRING,

 },

 {

  timestamps: false,

  validate: {

   userValidation() {

    if (this.firstName.length < 7) {

     throw new Error(“firstName length must be 7 or greater!”);

    }

    if (this.email.includes(“@mail.com”)) {

     throw new Error(“Email must not use mail.com address!”);

    }

   },

  },

 }

);

Leave a comment

Your email address will not be published. Required fields are marked *