Scala播放表单日期验证

时间:2016-10-03 16:10:41

标签: scala validation date playframework playframework-2.5

我正在使用Scala Play 2.5.x,我正在尝试进行日期验证。用户可以搜索包含此表单的项目,以及日期范围选项:fromDatetoDate

val searchForm = Form(
mapping(
  "itemID" -> nonEmptyText,
  "fromDate" ->  optional(date),
  "toDate" -> optional(date),
  "type" -> optional(text),
  "itemClass" -> optional(text),
  "status" -> optional(text),
  "component" -> nonEmptyText
)(SearchModel.apply)(SearchModel.unapply) verifying("To Date must be greater than From Date", f => f.toDate > f.fromDate))

Play已涵盖格式验证,但问题是toDate需要大于fromDate,如果输入其中一个日期,则还必须输入另一个日期。

如何在表单中实现这些条件?我是否应该在viewcontrollercase class等其他地方进行此验证?

2 个答案:

答案 0 :(得分:1)

您可以使用 .verifying

在表单上添加验证
    val searchForm = Form(
    mapping(
   "itemID" -> nonEmptyText,
   "fromDate" ->  optional(date).verifying("Invalid Date", date => true /* any condition or a function which checks the date condition*/),
   "toDate" -> optional(date),
   "type" -> optional(text),
   "itemClass" -> optional(text),
   "status" -> optional(text),
   "component" -> nonEmptyText
   )(SearchModel.apply)(SearchModel.unapply)

参考: - https://www.playframework.com/documentation/2.5.x/ScalaForms#Defining-ad-hoc-constraints

我希望你能提出这个问题。

答案 1 :(得分:1)

要实现验证需求,您可以将其保留在表单定义中并添加其他verifying

val searchForm = Form(
mapping(
  "itemID" -> nonEmptyText,
  "fromDate" ->  optional(date),
  "toDate" -> optional(date),
  "type" -> optional(text),
  "itemClass" -> optional(text),
  "status" -> optional(text),
  "component" -> nonEmptyText
)(SearchModel.apply)(SearchModel.unapply)
  verifying("You must provide zero or both dates", f => f.toDate.isEmpty && f.fromDate.isEmpty || f.toDate.isDefined && f.fromDate.isDefined)
  verifying("To Date must be greater than From Date", f => if (f.toDate.isDefined && f.fromDate.isDefined) f.toDate.get > f.fromDate.get else true)
)