Skip to content
Advertisement

How to display Sequelize validation error messages in Express API

I have this Organization model used in a Node.js/Express API with Sequelize ORM running MySQL. When I violate the 2-100 character rule under validation in the first code example below I get the classic err item from the catch block in the second code example, which doesn’t contain any information about the validation error.

I would like instead to display the validation error message you can see under validation { len: { msg: ...}} in the model. At least console.log it, and then later display it to the end user.

However, the Sequelize manual and any other information I can find don’t explain how I make use of this custom error message. So my question is how can I make use of it and display it.

Model:

'use strict'

const { Sequelize, DataTypes } = require('sequelize');
const db = require('./../config/db.js')

const Organization = db.define('organizations', {
  id: {
    type: DataTypes.UUID,
    defaultValue: Sequelize.UUIDV4,
    primaryKey: true,
    allowNull: false,
    unique: true,
    validate: {
      isUUID: {
        args: 4,
        msg: 'The ID must be a UUID4 string'
      }
    }
  },
  name: {
    type: DataTypes.STRING,
    required: true,
    allowNull: false,
    validate: {
      len: {
        args: [2, 100],
        msg: 'The name must contain between 2 and 100 characters.' // Error message I want to display
      }
    }
  },
  created_at: {
    type: DataTypes.DATE,
    required: true,
    allowNull: false
  },
  updated_at: {
    type: DataTypes.DATE,
    required: true,
    allowNull: false
  },
  deleted_at: {
    type: DataTypes.DATE
  }
},
{
  underscored: true,
  paranoid: true,
  tableName: 'organizations',
  updatedAt: 'updated_at',
  createdAt: 'created_at',
  deletedAt: 'deleted_at'
})

module.exports = Organization

Controller:

/**
 *  @description Create new organization
 *  @route POST /api/v1/organizations
 */

exports.createOrganization = async (req, res, next) => {
  try {
    const org = await Organization.create(
      req.body,
      {
        fields: ['name', 'type']
      })
    return res.status(200).json({
      success: true,
      data: {
        id: org.id,
        name: org.name
      },
      msg: `${org.name} has been successfully created.`
    })
  } catch (err) {
    next(new ErrorResponse(`Sorry, could not save the new organization`, 404))

// ^ This is the message I get if I violate the validation rule ^

  }
}

The Sequelize documentation for validation and constraints is found here: https://sequelize.org/master/manual/validations-and-constraints.html

The validation is built on Validatorjs (https://github.com/validatorjs/validator.js) which unfortunately also lacks practical info on the use of the validation object. I guess that means it must be self explanatory, but as I’m a noob I am lost.

Advertisement

Answer

I tried your same validation on my local project on firstName field and I could get sequelize error like this

console.log('err.name', err.name);
console.log('err.message', err.message);
console.log('err.errors', err.errors);
err.errors.map(e => console.log(e.message)) // The name must contain between 2 and 100 characters.

validation output

as you can see you can check if err.name is SequelizeValidationError and then loop over err.errors array and get message for field on path and rest other properties are also there.

Error Display example:

const errObj = {};
err.errors.map( er => {
   errObj[er.path] = er.message;
})
console.log(errObj);

you’ll get an object like

{ 
  firstName: 'The firstName must contain between 2 and 100 characters.',
  lastName: 'The lastName must contain between 2 and 100 characters.' 
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement