msgspec
msgspec copied to clipboard
Support bool value of "on" as true
Description
When creating a form in HTML we can use the checkbox input, which naturally maps to a bool in Python:
<input type="checkbox" name="is_example" checked />
Using FormData to submit that via a fetch or XMLHttpRequest request will follow the spec and product JSON in the request body like so:
{"is_example": "on"}
However, msgspec doesn't recognize it, and produces this error:
{"status_code":400,"detail":"Expected `bool`, got `str` - at `$.is_example`"}
This is very confusing, because a checkbox is essentially a bool, and other frameworks will usually do things like accept any truthy value. Luckily, there is a workaround right now by adding value="1" to the checkbox:
<input type="checkbox" name="is_example" checked value="1" />
I suspect there are probably other values that work as well. But I'd argue that "1" is just as much a str or bool as "on" is, and the official standard has to use "on" for checkboxes since the form element was added to HTML 2 in 1995, so it should probably be supported natively.