使用Sequelize.js进行自定义验证错误

jos*_*git 7 javascript node.js express sequelize.js

可以自定义错误

Sequelize.ValidationError

模型:

  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'
  });
Run Code Online (Sandbox Code Playgroud)

我的控制器:

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

  },
Run Code Online (Sandbox Code Playgroud)

我得到的错误是这样的:

{
  "name": "SequelizeValidationError",
  "message": "Validation error: Validation notEmpty failed",
  "errors": [
    {
      "message": "Validation notEmpty failed",
      "type": "Validation error",
      "path": "name",
      "value": {},
      "__raw": {}
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想传递这样的错误(只有路径和消息):

{
"name":"The field cannot be empty",
"other_field":"custom error message"
}
Run Code Online (Sandbox Code Playgroud)

我不知道我是否可以在模型中指定自定义消息,或者我必须创建一个函数来构建错误消息.

如果我必须构建一个函数,我该如何提取路径并自定义消息?

提前致谢.

net*_*hix 6

您可以捕获 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;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)


Ayo*_*ami 5

您可以为sequelize Validation指定自定义消息,您的代码将如下所示

\n\n
`var PaymentType = sequelize.define(\'payment_type\' , {\n  id: {\n  type: DataTypes.INTEGER(11),\n  allowNull: false,\n  primaryKey: true,\n  autoIncrement: true,\n  field: \'id\'\n},\ncode: {\n  type: DataTypes.STRING,\n  allowNull: false,\n  validate:{\n    notEmpty: {\n      args: true,\n      msg: \xe2\x80\x9ccode cannot be empty"\n    }\n  },\n  field: \'code\'\n},\nname: {\n  type: DataTypes.STRING,\n  allowNull: false,\n  validate:{\n    notEmpty: {\n      args: true,\n      msg: \xe2\x80\x9ccode cannot be empty"\n    }\n  },\n  field: \'name\'\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我将验证规则指定为一个对象,在上面的情况下,notEmpty应该是 true 所以我将其重构为一个对象,将属性设置argstrueie notEmptyshould be true,第二个属性msg包含我们的自定义消息

\n\n

notEmpty: {\n args: true,\n msg: \xe2\x80\x9ccode cannot be empty"\n }

\n


Chu*_*ran 3

您是否尝试像这样更改模型:

 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'
  });
Run Code Online (Sandbox Code Playgroud)

参考这个帖子