Lack of usage on validation #1765
-
I can only find "validate" in API doumetation, and some usage examples after searching through github issues, but there is no official validation usage example. So what is the suggested way of doing validation with custom error messages? |
Beta Was this translation helpful? Give feedback.
Answered by
jamonholmgren
Aug 17, 2021
Replies: 1 comment
-
We should add some examples to the documentation, for sure. Here's one example that might help: https://mobx-state-tree.js.org/API/#custom const DecimalPrimitive = types.custom<string, Decimal>({
name: "Decimal",
fromSnapshot(value: string) {
return new Decimal(value)
},
toSnapshot(value: Decimal) {
return value.toString()
},
isTargetType(value: string | Decimal): boolean {
return value instanceof Decimal
},
getValidationMessage(value: string): string {
if (/^-?\d+\.\d+$/.test(value)) return "" // OK
return `'${value}' doesn't look like a valid decimal number`
}
})
const Wallet = types.model({
balance: DecimalPrimitive
}) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
jamonholmgren
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We should add some examples to the documentation, for sure.
Here's one example that might help:
https://mobx-state-tree.js.org/API/#custom