node.js - 在 sequelize 中定义自定义验证

标签 node.js validation sequelize.js

我有带有验证的 User 模型。唯一不起作用的验证是这个。

User.init({
    confirmation: {
        type: DataTypes.STRING,
        allowNull: true,
        validate: {
            notNull: {
                msg: "Not null"
            },
            areEquals(value) {
                if (value !== this.password) {
                    throw new Error("Not Equals");
                }
            }
        },
    }
    // ...
})
areEquals 不执行。即使发送值,它也始终显示“非空冲突”

最佳答案

User.init({
    confirmation: {
        type: DataTypes.STRING,
        validate: {
            notNull: false, // this is boolean
            areEquals: (value) => { // Updated 

                console.log(this.password) // while insert new data, password is null

                if (value != this.password) {
                    console.log('**')
                    throw new Error("Not Equals");
                }

                return true // must return true
            }
        },
    },
});
测试
await db.user.upsert({
    name: '123123123',
    password: '123456',
    confirmation: '3456'
})

ERROR: Validation error: Not Equals,
Validation error: Not Equals

关于node.js - 在 sequelize 中定义自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66484791/

相关文章:

node.js - 如果套接字io房间为空,是否会自动销毁?

validation - iOS 7 中的 UITextField 输入验证

node.js - Sequelize 返回错误结果

c# - 验证器不阻止回发

mysql - 为什么 Id 只保存在数据库中而没有其他数据?

javascript - Sequelize app.post : why "TypeError: Cannot read property ' create' of undefined"?

node.js - Bigquery insertAll() 仅插入最后一行

angularjs - Angular/Node/Express/Passport 跨域问题 - 启用 CORS Passport Facebook 身份验证

javascript - Node.js bcrypt compare 为正确的密码返回 false

ruby-on-rails - 嵌套模型验证 - 错误不显示