【问题标题】:Sequelize - run validations if allowNull === false and the value is nullSequelize - 如果 allowNull === false 并且值为 null 则运行验证
【发布时间】:2019-01-29 20:53:49
【问题描述】:

我正在编写一个应用程序并使用 Sequelize 作为 ORM。我遇到过这个问题:我有一个模型,它有 2 个字段(为简单起见,实际上有更多字段),它们相互依赖,就像这样:

const Application = sequelize.define('application', {
    visa_required: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false
    },
    visa_passport_number: {
        allowNull: false,
        type: Sequelize.STRING,
        defaultValue: '',
        validate: {
            shouldBeSetIfVisaRequired(val) {
                if (this.visa_required && (typeof val !== 'string' || val.trim().length === 0)) {
                    throw new Error('Please fill in this field.');
                }
            }
        }
    }
});

因此,如果设置了visa_required 字段,则还应设置visa_passport_number

问题是,当我将true 传递给visa_required 并将null 传递给visa_passport_number 时,它会因application.visa_passport_number cannot be null 错误而失败。当我不传递此值时,它会正常(但保存为空字符串)。

我可以将allowNull: true 作为visa_passport_number 的参数传递,但是如果我将此值设置为null,则此验证将被忽略。

那么,我怎样才能实现我想要实现的目标呢?

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    那些字段级验证奇怪地处理 null (恕我直言)。您可能想尝试这样的行级验证:

    const Application = sequelize.define('application', {
    visa_required: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false
    },
    visa_passport_number: {
        allowNull: false,
        type: Sequelize.STRING,
        defaultValue: ''
        }
    },
    validate: {
        needPassportNumberIfVisaRequired() {
           if (this.visa_required && 
               (this.visa_passport_number === null
               || typeof this.visa_passport_number  !== 'string' 
               || this.visa_passport_number.trim().length === 0)) {
                    throw new Error('Please fill in the passport number field.');
                }
            }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多