验证带有空列表的表单

时间:2015-03-18 04:30:01

标签: playframework

目前,我有这个Form变量:

val submitRecapForm = Form(
    mapping(
        "recap_id" -> text,
        "recap_date" -> date,
        "submitted_id" -> text,
        "edited_id" -> text,
        "recap_items" -> list(
            mapping(
                "product_name" -> nonEmptyText,
                "product_id" -> nonEmptyText,
                "qty" -> number,
                "unit_name" -> nonEmptyText,
                "unit_multiplier" -> number,
                "sys_qty" -> number,
                "invoice_items" -> list (
                    mapping(
                        "sur_key" -> of[Long],   //5
                        "id" -> of[Long],        //2
                        "date" -> nonEmptyText,  //1
                        "name" -> nonEmptyText,  //3
                        "addr" -> nonEmptyText,  //0
                        "qty" -> number          //4
                    )(Invoice_items.apply)(Invoice_items.unapply)
                )
            )(Recap_items.apply)(Recap_items.unapply)
        )
    )(Recap.apply)(Recap.unapply)
)

奇怪的是,我可以提交带有recap_items空列表的表单。这是一个错误,还是有任何其他方式可以将其指定为nonEmpty nonEmptyText

1 个答案:

答案 0 :(得分:2)

您可以在Play框架中定义自己的验证约束。 之前,我还想使用表单验证来测试列表是否为空。

我使用了以下代码

def nonEmptyList[T]: Constraint[List[T]] = Constraint[List[T]]("constraint.required") { o =>
  if (o.nonEmpty) Valid else Invalid(ValidationError("error.required"))
}

val form: Form[A] = Form(
  mapping(
    "list" -> list(text).verifying(nonEmptyList)
  ) {
    (list) => A(list)
  } {
    param => Some((param.list))
  }
)