2012-04-26 50 views
10

我了解如何在Play 2中添加简单表单验证,例如nonEmptyText,但是我将如何实施更复杂的验证,例如“至少必须定义一个字段”?目前我在模型对象中抛出一个异常,如果它被所有的None初始化,但是这会产生一个令人讨厌的错误信息。我希望在表单页面上获得友好的错误消息。如何在Play 2中指定复杂的表单验证?

+0

适用于播放v1或播放V2这个问题!? – adis 2012-05-11 19:05:55

回答

9

您可以窝在你的表单定义mappings/tuples并添加映射,子映射,元组和子元组verifying规则。 然后在您的模板中,您可以使用form.errors("fieldname")为特定字段或组的字段检索错误。

例如:

val signinForm: Form[Account] = Form(
    mapping(
     "name" -> text(minLength=6, maxLength=50), 
     "email" -> email, 
     "password" -> tuple(
      "main" -> text(minLength=8, maxLength=16), 
      "confirm" -> text 
     ).verifying(
      // Add an additional constraint: both passwords must match 
      "Passwords don't match", password => password._1 == password._2 
     ) 
    )(Account.apply)(Account.unapply) 
) 

如果你有两个不同的密码,你可以在你的模板检索错误使用form.errors("password")

在这个例子中,你将不得不写自己的Account.applyAccount.unapply以处理(String, String, (String, String))

+1

酷,但不幸的是,这也意味着帐户不能成为案例类。我认为案例类不能重新定义不适用。 – schmmd 2012-05-11 20:43:45

+0

@schmmd其实Account.apply是case类的伴侣对象的一种方法 - > http://daily-scala.blogspot.fr/2009/09/companion-object.html。你可以自己写。 – iwalktheline 2012-05-12 14:32:37

+0

当然,但我的问题是“不适用”而不是“适用”。 – schmmd 2012-05-14 04:16:05

0

在玩!框架,你可以通过使用flash变量来显示友好的错误信息。你只需要写一些像;

flash.error("Oops. An error occurred"); 

给你的控制器。例如,这个错误信息将驻留在html页面上;

<h1>${flash.error}</h1> 

玩!框架会将错误消息放在找到这个$ {flash.error}的地方。

7

我改进了@ kheraud的接受答案。你可以把这个元组转换回单个字符串。这允许您使用默认的apply/unapply函数。

例子:

val signinForm: Form[Account] = Form(
    mapping(
     "name" -> text(minLength=6, maxLength=50), 
     "email" -> email, 
     "password" -> tuple(
      "main" -> text(minLength=8, maxLength=16), 
      "confirm" -> text 
     ).verifying(
      // Add an additional constraint: both passwords must match 
      "Passwords don't match", password => password._1 == password._2 
     ).transform(
      { case (main, confirm) => main }, 
      (main: String) => ("", "") 
     ) 
    )(Account.apply)(Account.unapply) 
) 
+0

+1 - 直到现在还没有看到 - 对于那些不可避免地会弹出的边缘情况来说,这可能是非常方便的事情。谢谢! – Techmag 2015-06-05 13:20:45

+0

这是完美的,因为您不必更改案例分类。 – haffla 2015-09-19 13:11:08