Error Message for Sequelize Validation Fails to Appear as Expected

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}

Answer №1

After some investigation, I discovered the solution - I needed to include a notNull message within 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',
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for an animation to complete even if it is stopped midway?

I am currently working on a media player project where I have implemented a scrolling marquee effect for the song meta information using JavaScript and CSS. The scrolling effect only occurs when the track is playing, and I achieve this by adding/removing ...

Is it possible to identify horizontal scrolling without causing a reflow in the browser?

If you need to detect a browser scroll event on a specific element, you can use the following code: element.addEventListener('scroll', function (event) { // perform desired actions }); In order to distinguish between vertical and horizontal ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

Struggling to launch the Node.js server on the OpenShift platform

Check out this snippet of code: var express = require('express'); var net = require('net'); var app = express(); var sock; //Establishing connection with mobile server on port 5132 console.log('Waiting for connection\nfrom ...

Conversation with form component in angular2

I am currently using ng2-bootstrap-modal. For adding a sample form to the example Confirm Dialog, check out ng2-bootstrap-modal. To change the template: <div class="modal-dialog"> <div class="modal-content"> <form [formGroup]="login ...

Using Rails to Pass Front-End JavaScript Data from an External API to the Controller

I need to retrieve coordinates from an external API, specifically the Google Maps API, and then send it to my controller. However, I am encountering a 500 internal server error when using jQuery/Ajax for this task. Researching the issue online suggests tha ...

Is the Mean.js user securely authenticated for authorization on this request?

I recently used meanjs to create a project and noticed that there are automatically generated hasAuthorization functions for crud modules. In the app/controllers/articles.server.controller.js file, they look something like this: exports.hasAuthorization = ...

What steps should be taken to enable express to accept external connections?

I've been working on implementing this code snippet in Node JS: #!/usr/bin/env node var debug = require('debug')('server_auth'); var app = require('../app'); app.set('port', process.env.PORT || 3000); var ser ...

The images in the React slick carousel appear to be slightly out of

I'm experiencing blurriness in my carousel when it animates with card items. Despite searching for a solution, I haven't found one yet. My tech stack includes Next.js and TypeScript. const ref = useRef<any>(); const settings = { arro ...

utilizing ajax to submit data with checkbox option

<html> <body> <input type="checkbox" checked="checked"> </body> </html> I am looking for a solution to pass the value of a checkbox as either 1 or 0 depending on its selection status. When the checkbox is checked, I want to s ...

Understanding Node.js document object

Hey, I'm currently trying to execute a JavaScript function on the server side using node.js, but I've encountered an issue. The function relies on accessing hidden values within the returned HTML using the document DOM, however, the document obje ...

Setting up Angular 6 on Azure Platform

I am currently facing challenges while trying to deploy a sample application on the azure portal. To start off, I decided to run some tests by creating an Angular app using 'ng new poc-pwa-angular-v2', and then pushed it to a Bitbucket repositor ...

Submitting a Complex JSON Object through a URL with Javascript

I am attempting to send a complex JSON Object in a URL input = { "id": 1, "sd": "123", "filter": { "h": 1,"road": true }, "legs": [{ "id": 1, "x1": -0.001, "y1": 51.122 }, { "id": 2, "x1": -12, "y1": 12 }] }; I have experimented with these methods data ...

The typography text exceeds the boundaries of the Material-UI CardContent

In the React Material-UI framework, I am working with a CardContent component that looks like this: <CardContent className={classes.cardContent}> <Typography component="p" className={classes.title} variant="title"> {this.props.post.title ...

What are the best practices for setting access permissions when using Azure AD authorization flow?

I am in the process of creating a small Next.js application with the following structure: Authenticate a user via Azure AD using Next-Auth Allow the user to initiate a SQL Database Sync by clicking a button within the app with the access token obtained du ...

How can I stop an element from losing focus?

One issue I'm facing is that when I have multiple elements with the tabindex attribute, they lose focus when I click on any area outside of them. The Problem - In traditional desktop applications, if an element is not able to receive focus, clicking ...

Is it possible to divide a text string into distinct arrays using spaces?

One method I am familiar with for splitting a string involves using the .split() method, like so: function split(txt) { return txt.split(' '); } When executed, this function would return ['hello', 'world'] if provided wi ...

Apply a border to the input field when the user enters or leaves the field, only if the value is

I am managing a few input fields and storing their information in an object. My goal is to click on an input field to focus on it, and if the field is empty or has a length greater than or equal to 0, I want it to display a red border. If I type somethin ...

Generating and verifying checksums for strings in Node JS: A step-by-step guide

I am in the process of rewriting a function in Node.js for generating and verifying checksums for payment transactions. I am new to coding in Node.js and need some guidance. The code I have received from the Service Provider needs to be converted into Nod ...

What is the method for transmitting a concealed attribute "dragable" to my component?

Currently, I have successfully integrated a here map into my project, but I am now tackling the challenge of adding draggable markers to this map. To achieve this, I am utilizing a custom package/module developed by my company. This package is designed to ...