gpt4 book ai didi

scala - 如何显示临时约束表单验证消息?

转载 作者:行者123 更新时间:2023-12-04 17:55:22 24 4
gpt4 key购买 nike

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
})
)

通过绑定(bind)错误,一些约束显示在我的表单中。 (就像 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
)

如果我做 .toStringformWithErrors我得到这个 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
})

但我不知道如何向用户显示“无效的用户名或密码”。 .toStringFormError formWithErrors列表是:
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'") 每次都给我“没有错误”。

最佳答案

实际上,一个表单可以有 errors附加到它,所以当来自请求的绑定(bind)验证约束失败时,会根据给定的表单创建一个新表单,但用 errors 填充.

此类错误列表由 FormError 组成它引用表单字段并覆盖 toString 以显示其嵌入消息。

这样,如果您希望一次显示所有消息,您可以简单地 formWithErrors.errors.mkString("<br>")例如(在您的模板中或闪烁它)。

方法很多,这里介绍一些常用的http://www.playframework.org/documentation/2.0.2/ScalaFormHelpers .您也可以定义自己的字段构造函数。

最后,我的建议是您应该使用助手 amap(例如 @inputText 和 co),因为它们已经包含显示助手、提示和 的逻辑。错误 有空的时候。

编辑

我错过了有关闪存问题的提示...您可能忘记添加 (implicit flash: Flash)给你模板参数列表。 (不要忘记在您的操作定义中将请求标记为隐式)

关于scala - 如何显示临时约束表单验证消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11385052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com