Search code examples
formsscalaplayframeworkplayframework-2.2

Show only one error message, on scala forms


Well, I had a minor issue with displaying errors in scala forms,

On my scala form for an individual field, I have done two checks, like:

    val startForm = Form(
        single(
          "fooField" -> text.verifying(LengthError, { Util.isLengthCorrect(_) }).verifying(EmptyError, { !_.isEmpty }),
))

So, when the error message in shown in the form, if both the check criteria aren't full-filled both error message are shown, when only one should have been shown.

Well I could show only the first error, manually,like this:

@for(error <- startForm.errors("fooField")) {
                            <dd class="error">@Messages(error.message,0)</dd>
                            }

But since I am using form helpers, the form helper will display error message itself. So what can be done to solve this problem.

@Update: Of course, here I have checked If fooField isEmpty or isCorrectLength, and logic states that we should check isCorrectLength only if the field isn't empty. But there are other conditions where I need two or more fooField.verifying() I just posed here a simple example of my problem.


Solution

  • You would have to create your own way of composing two Constraint[T] which will only evaluate the second if the first one passes. Something like this:

    def oneAtATime[T](first: Constraint[T], second: Constraint[T]) =
      new Constraint[T](None, Seq()) { t: T =>
        first(t) match {
          case Valid => second(t)
          case other => other
        }
      }