在我的模型中,我有
level: {
type: DataTypes.ENUM('state', 'service-area'),
allowNull: false,
validate: {
isIn: {
args: [
['state', 'service-area']
],
msg: 'level should be one of state,service-area'
}
}
},
assignedStates: {
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: true
},
assignedServiceAreas: {
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: true
},
我正在尝试添加验证器,如果level
是state
,那么assignedStates
不应该为空。我该怎么做呢?
你可以使用Model validations来做到这一点。第三个参数允许您验证整个模型:
const Levels = {
State: 'state',
ServiceArea: 'service-area'
}
const Location = sequelize.define(
"location", {
level: {
type: DataTypes.ENUM(...Object.values(Levels)),
allowNull: false,
validate: {
isIn: {
args: [Object.values(Levels)],
msg: "level should be one of state,service-area"
}
}
},
assignedStates: {
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: true
},
assignedServiceAreas: {
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: true
}
}, {
validate: {
assignedValuesNotNul() {
// Here "this" is a refference to the whole object.
// So you can apply any validation logic.
if (this.level === Levels.State && !this.assignedStates) {
throw new Error(
'assignedStates should not be null when level is "state"'
);
}
if (this.level === Levels.ServiceArea && !this.assignedServiceAreas) {
throw new Error(
'assignedSerivceAreas should not be null when level is "service-areas"'
);
}
}
}
}
);