Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Play form validation: required boolean isn't mandatory

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.

like image 775
psisoyev Avatar asked Oct 21 '22 06:10

psisoyev


1 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".

like image 134
estmatic Avatar answered Oct 25 '22 17:10

estmatic