Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 456
anatolhiman Avatar asked Sep 12 '20 02:09

anatolhiman


People also ask

What is validation error in Sequelize?

Validation Error. Thrown when the sequelize validation has failed. The error contains an errors property, which is an array with 1 or more ValidationErrorItems, one for each validation that failed.

How do I use validation in Sequelize?

To do that in Sequelize we can use validations and constraints. Validations are done by the Sequelize framework on the JavaScript level. We can provide custom validator functions or use predefined validators for this. If our data fails this validation then no SQL query will be made.

How do I validate a phone number in Sequelize?

phone: { type: Sequelize. STRING, allowNull: false, validate: { notNull: { args: true, msg: "You must enter Phone Number" }, len: { args: [11,11], msg: 'Phone Number is invalid' }, isInt: { args: true, msg: "You must enter Phone Number" }, } }, node. js.


1 Answers

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.' 
}
like image 174
Rohit Ambre Avatar answered Oct 13 '22 00:10

Rohit Ambre