Refinement and validation - where are docs? #2261
-
I can't find anything on refinement or validation. Or rather - the existing API docs are no better than reading source code. For instance, I have a model like: const productWeightModel = types.model({
weight: types.union(
types.model({
net: types.number,
}),
types.model({
gross: types.number,
tareWeight: types.number,
})
),
}) And I want to validate that How can I do that? |
Beta Was this translation helpful? Give feedback.
Answered by
coolsoftwaretyler
Apr 2, 2025
Replies: 1 comment 3 replies
-
Hey @OnkelTem - yeah sorry about the docs. Does this example help? import { types } from "mobx-state-tree";
const GrossWeightModel = types.model({
gross: types.number,
tareWeight: types.number,
});
const NetWeightModel = types.model({
net: types.number,
});
// Refinement to enforce `gross > tareWeight`
const ValidWeight = types.refinement(
types.union(NetWeightModel, GrossWeightModel),
(weight) => {
if ("gross" in weight) {
return weight.gross > weight.tareWeight;
}
return true; // Net weight model is always valid
}
);
const ProductWeightModel = types.model({
weight: ValidWeight,
});
const validProduct = ProductWeightModel.create({
weight: { gross: 10, tareWeight: 5 },
});
// ✅ Works fine
const invalidProduct = ProductWeightModel.create({
weight: { gross: 5, tareWeight: 10 },
});
// ❌ Throws an error: "Error while converting ... Gross weight must be greater than tare weight" If you like that, I'd be happy to accept a PR to the docs site adding it. :) |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
OnkelTem
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @OnkelTem - yeah sorry about the docs. Does this example help?