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}
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',
});