javascript - 在保存之前使用 Sequelize Build 构建并验证模型

标签 javascript mysql node.js sequelize.js

我遇到了一种情况,我想通过 Stripe 接受付款,但首先需要验证表单输入。

一旦表单验证,在成功函数中我将调用 Stripe 并确保其正常。如果两者都很好,我将处理付款,然后保存帖子。

我正在努力事先对帖子进行验证 - 请记住,我还不想保存它。

我正在使用 Express/Node.js 和 Sequelize - MySQL

 var post = Post.build({
    title: req.body.title,
    description: req.body.description,
  })

我尝试过类似的操作,但在我的控制台中它显示全红色。

post.validate().error(err => {
    console.log(err)
  })

下面这个解决方案是我在网上找到的,不起作用

//   if (errors) {
//     for (var prop in errors) {
//       console.log(prop.error)
//       if (errors.hasOwnProperty(prop)) {
//         console.log(errors[prop])
//           console.log("Errors for field " + prop + ": ");
//             // for (var i = 0; i < errors[prop].length; i++) {
//             //          errors[prop][i];
//             // }
//     }
//   }

我想立即返回所有表单错误,然后当通过时,执行我的 Stripe,然后当通过时,保存两者。

最佳答案

要使用 sequelize 验证字段并得到重大错误,指出问题出在哪里,您必须在模型定义中使用 validate: {} 属性以及要检查的规则。

关于文档:

Model validators allow you to specify format/content/inheritance validations for each attribute of the model. Validations are automatically run on create, update and save. You can also call validate() to manually validate an instance.

Validate the attributes of this instance according to validation rules set in the model definition.

示例:

module.exports = (sequelize, DataTypes) => {
  const test = sequelize.define(
    'test',
    {
      testDate: {
        allowNull: false,
        type: DataTypes.Date,
        defaultValue: DataTypes.NOW,
        validate: {
          isDate: true,
        },
      }
    },
    {
      freezeTableName: true,
      timestamps: false,
    }
  )
}

手动验证:

const item = await test.build(object)
const validatedItem = await item.validate()

未通过验证的结果: enter image description here

您可以在这里找到更多内容:

https://sequelize.org/master/class/lib/model.js~Model.html#instance-method-validate https://sequelize.org/master/manual/validations-and-constraints.html

关于javascript - 在保存之前使用 Sequelize Build 构建并验证模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57814935/

相关文章:

javascript - 使用 Ajax 延长 PHP session 超时

javascript - 在javascript中得到错误的总数

mysql错误 "Can' t通过套接字 '/var/run/mysqld/mysqld.sock"连接到本地MySQL服务器

php - 基于两个参数将 SQL 查询转换为 Eloquent Laravel

javascript - javascript,jquery 中的作用域变量

javascript - 始终在 Dygraphs 的图例中显示标签

mysql - 带有 TIMESTAMP(3) 列的 Spark JDBC DataFrame

javascript - 在没有全局 gulp 的情况下使用 gulp//edit : and without linking to the bin js file

javascript - Node : check latest version of package programmatically

node.js - 生产 Angular 应用程序连接到本地 Express 实例而不是生产 Express 实例