我有一个表格,预计会有一些数字......我很难核实是否已经提交,或者没有回复说明需要的信息,我尝试了以下内容但没有工作的案例:
"orderBy" -> number.verifying("The order is required",_.isInstanceOf[Int])
"orderBy" -> number.verifying("The order is required",_>0)
有什么想法吗?
答案 0 :(得分:1)
如果orderBy
未提交Form
,则会返回FormError
,其中包含密钥error.required
。
我假设你的意思是提交空String
而不是数字。您尝试的问题是永远不会达到verifying
函数,因为空String
不会使其超过number
验证程序。
我唯一能想到的是制作一个自定义Mapping[Int]
,首先检查字段是否为空,然后检查它是否有效Int
。
val requiredNumber: Mapping[Int] = Forms.nonEmptyText
.verifying("Must be numeric", i => Try(i.toInt).isSuccess || i.isEmpty)
.transform[Int](_.toInt, _.toString)
并测试:
scala> val form = Form(mapping("orderBy" -> requiredNumber)(identity)(Some(_)))
scala> form.bind(Map("orderBy" -> "1")).value
res24: Option[Int] = Some(1)
scala> form.bind(Map("orderBy" -> "")).errors
res26: Seq[play.api.data.FormError] = List(FormError(orderBy,List(error.required),WrappedArray()))
scala> form.bind(Map("orderBy" -> "aa")).errors
res27: Seq[play.api.data.FormError] = List(FormError(orderBy,List(Must be numeric),WrappedArray()))
scala> form.bind(Map("orderByzzz" -> "2")).errors
res28: Seq[play.api.data.FormError] = List(FormError(orderBy,List(error.required),List()))