玩! Framework 2.0:使用其他字段验证表单中的字段 [英] Play! framework 2.0: Validate field in forms using other fields

查看:95
本文介绍了玩! Framework 2.0:使用其他字段验证表单中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在剧中!框架,使用Scala,说我的表单如下:

In the play! framework, using scala,say that i have a form such as follows:

import play.api.data._
import play.api.data.Forms._
import play.api.data.validation.Constraints._

case class User(someStringField: String, someIntField: Int)

val userForm = Form(
  mapping(
    "someStringField" -> text,
    "someIntField" -> number verifying(x => SomeMethodThatReceivesAnIntAndReturnsABoolean(x))
  )(User.apply)(User.unapply)

)

其中SomeMethodThatReceivesAnIntAndReturnsABoolean是一种在int上执行一些逻辑以对其进行验证的方法.

where SomeMethodThatReceivesAnIntAndReturnsABoolean is a method that performs some logic on the int to validate it.

但是,我希望能够在验证someIntField时考虑someStringField的值,有没有办法在游戏框架的形式中实现这一点?我知道我可以做类似的事情:

However, i would like to be able to consider the value of the someStringField when validating the someIntField, is there a way to achieve this in play framework's forms? I know that i can do something like:

val userForm = Form(
  mapping(
    "someStringField" -> text,
    "someIntField" -> number 
  )(User.apply)(User.unapply)
.verifying(x => SomeFunctionThatReceivesAnUserAndReturnsABoolean(x))

然后我将整个可用的用户实例传递给验证功能.这种方法的问题在于,所产生的错误将与整个表单相关联,而不是与someIntField字段相关联.

and then i would have the entire user instance available passed to the validation function. The problem with that approach is that the resulting error would be associated with the entire form instead of being associated with the someIntField field.

是否可以同时获取所有内容,使用另一个字段验证一个字段并维护与我要验证的特定字段(而不是整个表格)相关的错误?

Is there a way to get both things, validate a field using another field and maintain the error associated to the specific field i wish to validate, instead of the entire form?

推荐答案

根据其他字段的值,我对字段添加验证具有相同的要求.我不确定在惯用的PLAY 2.2.1中如何完成此操作,但是我想出了以下解决方案.在这种用法中,我将内置的映射"降级为一个简单的类型转换器,并在"validateForm"方法中应用了高级字段间"验证.映射:

I have the same requirements with adding validation to fields depending on the value of other fields. I´m not sure how this is done in idiomatic PLAY 2.2.1 but I came up with the following solution. In this usage I´m degrading the builtin "mapping" into a simple type converter and apply my "advanced inter field" validation in the "validateForm" method. The mapping:

val userForm = Form(
mapping(
  "id" -> optional(longNumber),
  "surename" -> text,
  "forename" -> text,
  "username" -> text,
  "age" -> number
)(User.apply)(User.unapply)
)

private def validateForm(form:Form[User]) = {
  if(form("username").value.get == "tom" || form("age").value.get == "38") {
    form
      .withError("forename", "tom - forename error")
      .withError("surename", "tom - surename error")
  }
  else
    form
}

def update = Action { implicit request =>
  userForm.bindFromRequest.fold({
    formWithErrors => BadRequest(users.edit(validateForm(formWithErrors)))
  }, { user => 
    val theForm = validateForm(userForm.fill(user))
    if(theForm.hasErrors) {
      BadRequest(users.edit(theForm))
    } else {
      Users.update(user)
      Redirect(routes.UsersController.index).flashing("notice" -> s"${user.forename} updated!")
    }
  }) 
} 

即使它可以工作,我仍在紧急寻找更惯用的版本...

Even though it works I´m urgently searching for a more idiomatic version...

编辑:在惯用播放中使用自定义play.api.data.format.Formatter,有关更多信息,请参见http://workwithplay.com/blog/2013/07/10/advanced-forms-techniques/-这可让您以编程方式向表单添加错误.我的格式化程序如下:

Use a custom play.api.data.format.Formatter in idiomatic play, more on http://workwithplay.com/blog/2013/07/10/advanced-forms-techniques/ - this lets you programmatically add errors to a form. My Formatter looks like this:

val usernameFormatter = new Formatter[String] {

override def bind(key: String, data: Map[String, String]): Either[Seq[FormError], String] = {
  // "data" lets you access all form data values
  val age = data.get("age").get
  val username = data.get("username").get
  if(age == "66") {
    Left(List(FormError("username", "invalid"), FormError("forename", "invalid")))
  } else {
    Right(username)
  }
}

override def unbind(key: String, value: String): Map[String, String] = {
  Map(key -> value)
}
}
}

像这样在表单映射中注册:

Registered in the form mapping like this:

mapping(
[...]
  "username" -> of(usernameFormatter),
[....]

这篇关于玩! Framework 2.0:使用其他字段验证表单中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆