【问题标题】:Verifying the existence of a number in a Play Scala form验证 Play Scala 表单中是否存在数字
【发布时间】:2014-12-22 20:37:08
【问题描述】:
我有一个表单,其中有一个预期的数字...我很难验证它是否已提交并返回一条消息说它是必需的,我尝试了以下情况但没有一个成功:
"orderBy" -> number.verifying("The order is required",_.isInstanceOf[Int])
"orderBy" -> number.verifying("The order is required",_>0)
有什么想法吗?
【问题讨论】:
标签:
scala
playframework
playframework-2.2
playframework-2.1
playframework-2.3
【解决方案1】:
如果orderBy 根本没有与Form 一起提交,那么它将返回一个带有error.required 键的FormError。
我假设您的意思是提交空的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()))