Custom Validation Error Using Sequelize.js

You can customize the error from

Sequelize.ValidationError

Model:

  var PaymentType = sequelize.define('payment_type' , {
      id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      field: 'id'
    },
    code: {
      type: DataTypes.STRING,
      allowNull: false,
      validate:{
        notEmpty: true
      },
      field: 'code'
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate:{
        notEmpty: true
      },
      field: 'name'
    }
  }, {
    timestamps: true,
    paranoid: false,
    underscored: true,
    freezeTableName: true,
    tableName: 'payment_types'
  });

My controller:

  update(req, res) {
      paymentType
        .update(req.body, {
          where: {
            id: req.params.id
          }
        })
        .then( updatedRecords => {
          res.status(200).json(updatedRecords);
        })
        .catch(Sequelize.ValidationError, error => {
          res.status(400).json(error);
        })
        .catch( error => {
          res.status(500).json(error);
        });

  },

The errors I get are as follows:

{
  "name": "SequelizeValidationError",
  "message": "Validation error: Validation notEmpty failed",
  "errors": [
    {
      "message": "Validation notEmpty failed",
      "type": "Validation error",
      "path": "name",
      "value": {},
      "__raw": {}
    }
  ]
}

I want to pass errors like this (path and message only):

{
"name":"The field cannot be empty",
"other_field":"custom error message"
}

I do not know if I can specify a custom message in the model or do I need to create a function to create error messages.

If I need to create a function, how can I extract the path and configure the message?

Thanks in advance.

+7
source share
2 answers

You are trying to change the model as follows:

 var PaymentType = sequelize.define('payment_type' , {
      id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      field: 'id'
    },
    code: {
      type: DataTypes.STRING,
      allowNull: false,
      validate:{
        notEmpty: {
          msg: "The field cannot be empty"
        }
      },
      field: 'code'
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate:{
        notEmpty: {
          msg: "The field cannot be empty"
        }
      },
      field: 'name'
    }
  }, {
    timestamps: true,
    paranoid: false,
    underscored: true,
    freezeTableName: true,
    tableName: 'payment_types'
  });

Link to this post

0
source

Sequelize ValidationError ValidationErrorItem ( ValidationErrorItem.validatorKey). .

try {
 // sequelize custom logic here
} catch(e) {
    const messages = {};
    if (e instanceof ValidationError) {
        e.errors.forEach((error) => {
            let message;
            switch (error.validatorKey) {
                case 'isEmail':
                    message = 'Please enter a valid email';
                    break;
                case 'isDate':
                    message = 'Please enter a valid date';
                    break;
                case 'len':
                    if (error.validatorArgs[0] === error.validatorArgs[1]) {
                        message = 'Use ' + error.validatorArgs[0] + ' characters';
                    } else {
                        message = 'Use between ' + error.validatorArgs[0] + ' and ' + error.validatorArgs[1] + ' characters';
                    }
                    break;
                case 'min':
                    message = 'Use a number greater or equal to ' + error.validatorArgs[0];
                    break;
                case 'max':
                    message = 'Use a number less or equal to ' + error.validatorArgs[0];
                    break;
                case 'isInt':
                    message = 'Please use an integer number';
                    break;
                case 'is_null':
                    message = 'Please complete this field';
                    break;
                case 'not_unique':
                    message = error.value + ' is taken. Please choose another one';
                    error.path = error.path.replace("_UNIQUE", "");
            }
            messages[error.path] = message;
        });
    }
}
0

Source: https://habr.com/ru/post/1675757/


All Articles