I have a "group" of the following inputs:
Text input 1 is always required. Text input 2 is only required if the checkbox is checked. How can I achieve this type of validation with play? Currently I have something like this:
val myForm: Form[MyData] = Form(
mapping(
"text1" -> text.verifying("Text1 is required", !_isEmpty),
"text2" -> text.verifying("Text2 is required", !_isEmpty),
"check" -> boolean
)
But clearly this is not what I want since it will always require text2. Is there a way to compose this to achieve this interdependent validation?
update based on wheaties suggestion: This solution worked, however it has some quirks that I need to overcome:
I looked at the custom validators the play supports, but I do not see how I can use them to operate across multiple fields. The example they show applies only the the form field that is being validated with no obvious way to reference other inputs in the form.
You can see from the documentation that they allow for ad-hoc validations on the form objects you create (see documents.) What you can do is make a validator:
def validate(text1: String, text2: String, check: Boolean) = if(check) text2.nonEmpty else true
val myForm: Form[MyData](
mapping("text1" -> text.verifying("Text1 is required", !_isEmpty))
)(MyData.unapply)(MyData.apply) verifying ("Text2 is required if check box checked", {
case data => validate(data.text2, data.check)
})
which should give you what you want but I'd also check out their custom validators section as well (since they recommend this as a good route to follow.)