I am trying to implement Sequelize model validation in order to validate a form field. When the book or author fields are left empty, I want this message to be displayed:
Oops! An error occurred. "Title" is required. "Author" is required.
The issue I'm facing with my code is that the current error message reads as follows:
Oops! An error occurred. Book.title cannot be null. Book.author cannot be null
I would appreciate some guidance. Below is the code for my Book model:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Book extends Model {
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;
};
Below is specific code from 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}