进行年龄验证(从出生日期开始)

时间:2019-04-16 08:04:59

标签: javascript validation date sequelize.js

我希望我的用户在注册时早于8岁。 我按照该示例创建了自己的验证器:http://docs.sequelizejs.com/manual/models-definition.html#validations。 在这里:

// In a model file 

module.exports = (sequelize, Sequelize) => {
  return sequelize.define('Utilisateur', {
    // ...
    DateNaissance: {
      type: Sequelize.DATEONLY,
      validate: {
        isOldEnough(value) {
          let ageCheck = new Date(Date.now());
          ageCheck.setFullYear(ageCheck.getFullYear-8);
          if (ageCheck < value) {
            throw new Error('Too young');
          }
        }
      }
    }
  }, {
      timestamps: false
    });
}

问题是,当我尝试注册此用户时,它可以工作,但不应该:

{
    "email": "test@test.com",
    "password": "12345678",
    "prenom": "prenomTest",
    "nom": "nomTest",
    "dateNaissance": "2018-03-03", // <<--
    "nomVillage": "villageTest",
    "NPA": "9999",
    "noRue": 42,
    "nomRue": "Chemin du test"
}

我还想知道是否可以使用Sequelize模型真正做到这一点,因为模型定义将只完成一次?也许我必须在触发器中执行此检查?

1 个答案:

答案 0 :(得分:0)

我终于可以用钩子(beforeCreate)做到这一点:

// ...
DateNaissance: {
      type: Sequelize.DATEONLY,
      validation: {
        isDate: true,
      }
    }
  }, {
      timestamps: false,
      hooks: {
        beforeCreate: function (user, options) {

          let ageCheck = new Date();
          ageCheck.setFullYear(ageCheck.getFullYear() - 8);
          let birthDate = new Date(user.DateNaissance);
          if (ageCheck < birthDate) {
            throw new Error('Too young');
          }
        }
      }
    });
}

hooks doc