播放验证-具有特定字段错误的自定义表单字段验证 [英] Play Validation - Custom form field validation with specific field error

查看:87
本文介绍了播放验证-具有特定字段错误的自定义表单字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

case class Address(
  address1: String,
  city: String,
  state: String,
  postal: String,
  country: String
)

Form(
    mapping = mapping(
      "address1" -> nonEmptyText,
      "city" -> nonEmptyText,
      "state" -> nonEmptyText,
      "postal" -> nonEmptyText,
      "country" -> nonEmptyText
    )(Address.apply)(Address.unapply).verifying("Invalid Postal Code!", validatePostal _)
)

def validatePostal(address: Address): Boolean = {
    address.country match {
      case "US" | "CA" =>
        val regex: Regex = ("^(\\d{5}-\\d{4}|\\d{5}|\\d{9})$|^([a-zA-Z]\\d[a-zA-Z]( )?\\d[a-zA-Z]\\d)$").r
        regex.pattern.matcher(address.postal).matches()
      case _ => false
    }
}    

在邮政编码上方进行表单验证时,如果美国或加拿大的邮政编码无效,表单上会显示全局错误,则效果很好.

Above form validation for postal code works fine with global error displayed on form for invalid US or Canadian postal codes.

我希望将错误显示为字段旁边的字段错误,而不是显示为全局错误(在我的情况下显示在表格顶部).

I would like to show the error as field error right next to the field than as global error which in my case is shown on top of the form.

是否有一种方法可以使用内置的Form约束或验证方法来代替FormError来实现此目的?

Is there a way to use inbuilt Form constraints or verification methods to achieve this instead of FormError's?

推荐答案

您可以将约束添加到字段中.然后更新validatePostal以接受两个值的元组.

You can add the constraint to the field. Then update validatePostal to accept a tuple of the two values instead.

Form(
  mapping = mapping(
    "address1" -> nonEmptyText,
    "city" -> nonEmptyText,
    "state" -> nonEmptyText,
    "postal" -> tuple(
      "code" -> nonEmptyText,
      "country" -> nonEmptyText
    ).verifying("Invalid Postal Code!", validatePostal _),
  )((address1, city, state, postal) => Address(address1, city, state, postal._1, postal._2))((address: Address) => Some((address.address1, address.city, address.state, (address.postal, address.country))))
)

模板:

@inputText(
  addressForm("postal.code"), 
  '_label -> "Postal code",
  '_help -> "Please enter a valid postal code.",
  '_error -> addressForm.error("postal")
)

这篇关于播放验证-具有特定字段错误的自定义表单字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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