【发布时间】:2012-07-08 06:16:13
【问题描述】:
ScalaForms
在链接here 的示例中,有这个关于表单验证的示例:
// You can also define ad-hoc constraints on the fields:
val loginForm = Form(
tuple(
"email" -> nonEmptyText,
"password" -> text
) verifying("Invalid user name or password", fields => fields match {
case (e, p) => User.authenticate(e,p).isDefined
})
)
由于绑定错误,一些约束会显示在我的表单中。 (就像nonEmptyText,它在字段后面有一个额外的行,说明This field is required。见:
loginForm.bindFromRequest.fold(
formWithErrors => // binding failure, you retrieve the form containing errors,
value => // binding success, you get the actual value
)
如果我对formWithErrors 执行.toString,我会得到nonEmptyText 约束:
Form(ObjectMapping2(<function2>,<function1>,(Email adress,FieldMapping(,List(Constraint(Some(constraint.required),WrappedArray())))),(Password,FieldMapping(,List(Constraint(Some(constraint.required),WrappedArray())))),,List(Constraint(None,List()))),Map(Password -> test, Email adress -> ),List(FormError(Email adress,error.required,WrappedArray())),None)
后半部分是FormError 列表:List(FormError(Email adress,error.required,WrappedArray())),None) 这是一个案例类:case class FormError (key: String, message: String, args: Seq[Any]),其中key 定义为:The error key (should be associated with a field using the same key).。
FieldConstructor 将其选中并使“电子邮件地址”输入框变为红色并添加错误消息(“此字段为必填项”)。
显示临时约束?
所以当表单字段都填满时,检查用户名和密码:
verifying("Invalid user name or password", fields => fields match {
case (e, p) => User.authenticate(e,p).isDefined
})
但我不知道如何向用户显示“无效的用户名或密码”。 formWithErrors 的FormError 列表中的.toString 是:
List(FormError(,Invalid user name or password,WrappedArray())),None)
Key 部分为空。
问题
如何显示临时错误?
我什至尝试过:
BadRequest( views.html.test( formWithErrors ) ).flashing( "error" -> "Invalid user name or password." ) },
但由于某种原因,它也不能通过 Flash 工作 :(。这个 @flash.get("error").getOrElse("no 'error'") 每次都给我“没有错误”。
【问题讨论】:
-
你有没有想过如何让密钥出现在错误中?我有同样的问题。