I've found interesting thing in Play! frameworks form validation. For example I have such form:
case class Foo(mystring: String, myint: Int, mybool: Boolean) { // doing cool stuff here }
val myForm = Form(
mapping(
"mystring" -> text,
"myint" -> number,
"mybool" -> boolean
)(Foo.apply)(Foo.unapply))
When I'm binding data without "mybool" present in my Json, validation passes and creates an object with "mybool = false". This is quite strange behavior, as if I will pass the same data, but without "mystring" field I will get Validation Errors: Map(mystring -> error.required)
which I expect to see - as the field is missing.
If I'm making the boolean field optional, but I'm manually adding such check:
"mybool" -> optional(boolean).verifying("mybool.required", _.isDefined)
And bind data without the field I'm getting the expected error:
Validation Errors: Map(mybool -> mybool.required)
Example data set:
{
"mystring": "stringHere",
"myint": 33
}
Why required check doesn't work for Boolean? What is the best workaround for it? Is it a Play! bug or I just don't understand something?
Thanks for your answers.
I would imagine it's by design. Typically if you have a boolean field then you would bind that to an HTML checkbox. If the box is checked when the form is submitted then all works as expected; however, if the box isn't checked then browsers don't send the field name with the submitted data. Basically, there is no different between an unchecked box and the element not existing at all, so Play has to assume (for boolean fields) that the value is "false".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With