2017-12-14 3 views
4

は、私がlevelその後assignedStatesがnullであってはならないstateであればバリデータを追加しようとしている値に依存するカスタムSequelizeバリデーターを使用できますか?私のモデルで

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 
     }, 

を持っています。それをどうやってやりますか?

答えて

1

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"' 
 
     ); 
 
     } 
 
     } 
 
    } 
 
    } 
 
);

: あなたが全体のモデルを検証することを可能にする3番目のパラメータがあります
関連する問題