Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
Sequelize Validation Error Message Not Displaying Correctly

I am trying to use Sequelize model validation to validate a form field. If the book or author fields are empty, this message should displayed:

Oops an error Occurred! "Title" is required. "Author" is required.

The problem I am having with my code is that the message currently reads:

Oops an error Occurred! Book.title cannot be null. Book.author cannot be null

I would be grateful for some assistance. Here is my Book model code:

'use strict';

const {
  Model
} = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class Book extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  Book.init({
    title: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: {
          msg: '"Title" is required'
        }
      }
    },
    author: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: {
          msg: '"Author" is required'
        }
      }
    }, 
    genre: DataTypes.STRING,
    year: DataTypes.INTEGER
  }, {
    sequelize,
    modelName: 'Book',
  });
  return Book;
};

Here is the some specific code in my routes file:

/* Post new book to database */
router.post('/', asyncHandler(async (req,res) => {
  let book;
  try {
    book = await Book.create(req.body);
    res.redirect('/books');
  } catch (error) {
    if (error.name === "SequelizeValidationError") {
      book = await Book.build(req.body);
      res.render('books/new_book', { book, errors: error.errors, title: "New Book" });
    } else {
      throw error;
    }  
  }
}));

/* Update book info in database */
router.post('/:id', asyncHandler(async (req,res) => {
  let book;
  try {
    book = await Book.findByPk(req.params.id);
    if (book) {
      await book.update(req.body);
      res.redirect("/books");
    } else {
      res.sendStatus(404);
    }
  } catch (error) {
    if(error.name === "SequelizeValidationError") {
      book = await Book.build(req.body);
      book.id = req.params.id;
      res.render("books/update_book", { book, errors: error.errors, title: "Update Book" })
    } else {
      throw error;
    }
  }
}));

Here is my pug code to display the errors:

if(errors)
  h2.error Oops an error occurred!
  ul.error
    each error in errors
      li #{error.message}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I figured it out, I needed to add a notNull message in the validate object in the Book model

Book.init({
    title: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: { msg: '"Title" is required' },
        notEmpty: { msg: '"Title" is required' }
      }
    },
    author: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: { msg: '"Author" is required' },
        notEmpty: { msg: '"Author" is required' }
      }
    }, 
    genre: DataTypes.STRING,
    year: DataTypes.INTEGER
  }, {
    sequelize,
    modelName: 'Book',
  });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda