Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda