首页 文章

Sequelize - 如何在更新时部分验证?

提问于
浏览
3

更新时,Sequelize会对所有字段/属性执行验证(除了allowNull设置为true的那些) - 即使只修改了一个字段子集(通过updateAttributes) . 是否可以仅验证要更新的字段?也就是说,要部分验证模型实例?

我有以下用户表:

create table users (
    id serial primary key,
    email varchar(192) not null,
    username varchar(32) not null,
    password char(32) not null,

    unique(username)
);

型号定义:

// Inside User model definition:
email: { ... },
username: { ... },
password: {
    type: DataTypes.STRING,
    validate: {
        is: {
            // Reference: http://stackoverflow.com/a/1559788
            args: ['(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[-+_!@#$%^&*.,?]).+'],
            msg: "Password must contain one at least one uppercase, lowercase, number, and special character"
        }
    }
},

在创建和检索用户记录时,所有工作都按预期工作 . 不幸的是,当我尝试更新现有用户的电子邮件地址时,密码验证失败 . 发生这种情况是因为我存储了每个用户密码的散列版本(十六进制摘要),该密码不包含任何特殊字符(验证所需) .

一种可能的解决方法是仅在创建用户时应用此验证;但是,这会引入用户更改密码时验证的问题 .

理想情况下,密码验证仅在创建新用户或更新现有用户的密码字段时应用 . 有任何想法吗?

1 回答

相关问题