Sequelize IsIn验证失效:非法值仍存入数据库问题求助
It looks like the main issue here is a simple typo in your model configuration that's preventing Sequelize from applying your validation rules. Let's walk through the fixes step by step:
1. Correct the Typo in Model Validation
You have a misspelled key validade instead of validate in your purchase_unit field definition. Sequelize doesn't recognize this misspelled key, so none of your validation rules (including the isIn check) are being executed when saving records.
Here's the corrected model field code:
purchase_unit: { type: DataTypes.STRING, allowNull: false, validate: { // Fixed the typo here notNull: { msg: 'The field "purchase unit" must be entered' }, notEmpty: { msg: 'The field "purchase unit" cannot be empty' }, isIn: { args: [["Und", "Pct"]], msg: 'Entry not allowed for field "purchase unit"' } } }
2. Ensure Validations Are Triggered on Save
Double-check that you're using Sequelize methods that automatically run validations. Most common methods like Model.create() and instance.save() run validations by default. If you're using bulkCreate(), you'll need to explicitly add the validate: true option to enforce validations for bulk operations.
For example, creating a record should look something like this:
const newProduct = await Product.create({ // other fields... purchase_unit: req.body.purchase_unit });
If you're updating an existing record:
const product = await Product.findByPk(productId); product.purchase_unit = req.body.purchase_unit; await product.save(); // This runs validations by default
3. Optional: Clean Up Frontend Options (For Better UX)
While backend validation is the critical safeguard, if you don't want users to even see the unallowed options (m², g, Kg, etc.), you can remove them from your frontend dropdown. This will prevent users from selecting invalid values in the first place, improving the user experience.
Your corrected frontend select might look like this:
<select value={productPurchaseUnit} onChange={e => setProductPurchaseUnit(e.target.value)} > <option value="Und">Und</option> <option value="Pct">Pct</option> </select>
Once you fix the typo in your model, Sequelize will start enforcing the isIn validation, and any attempts to save values outside of ["Und", "Pct"] will throw an error with your custom message, preventing invalid data from being stored in the database.
内容的提问来源于stack exchange,提问作者Victor Nogueira

