Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 处理带有自定义验证的可选字段的表单映射_Scala_Playframework - Fatal编程技术网

Scala 处理带有自定义验证的可选字段的表单映射

Scala 处理带有自定义验证的可选字段的表单映射,scala,playframework,Scala,Playframework,我的表单如下所示: case class RegistrationForm(department: Option[String], name: String, email: String, employeeId: Option[Int]) 现在我需要做的是,如果用户输入了department输入,那么employeeId应该是None。如果他们将部门留空,则员工ID将是必填字段 我的映射当前是这样的,但它不处理此逻辑: val registrationForm = Form( mappin

我的表单如下所示:

case class RegistrationForm(department: Option[String], name: String, email: String, employeeId: Option[Int])
现在我需要做的是,如果用户输入了
department
输入,那么
employeeId
应该是None。如果他们将
部门
留空,则
员工ID
将是必填字段

我的映射当前是这样的,但它不处理此逻辑:

val registrationForm = Form(
  mapping(
    "department" -> optional(String)
    "name" -> nonEmptyText,
    "email" -> nonEmptyText,
    "employeeId" -> optional(number)
  )(RegistrationForm.apply)(RegistrationForm.unapply)
)
另外,在我的表单中,我如何创建一个隐藏的输入字段并将其绑定到我的表单属性,因为有时我的url类似于:

/users/register?employeeId=293838
所以我想创造:

<input type="hidden" name="employeeId" value="???" />


因此,此employeeId隐藏输入应绑定到表单。

在表单字段成功绑定到案例类后,您可以使用
验证
在表单字段之间构建约束

val registrationForm = Form(
    mapping(
        "department" -> optional(String)
        "name" -> nonEmptyText,
        "email" -> nonEmptyText,
        "employeeId" -> optional(number)
     )(RegistrationForm.apply)(RegistrationForm.unapply)
    .verifying("Some error message..", reg => 
        (reg.department.isEmpty || reg.employeeId.isEmpty) && (reg.department.nonEmpty || reg.employeeId.nonEmpty)
    )
)
verifying
的第一个参数是当约束被破坏时要使用的错误消息,第二个参数是要绑定到的case类的函数,它返回
布尔值。如果函数返回
false
,则
表单将包含全局错误。在我的例子中,我不能100%确定这就是你的逻辑,因为你的措辞有点奇怪(听起来像是在描述排他或)。如果需要,您还可以将多个
验证
操作链接在一起


我不确定你关于隐藏字段的问题是什么。html表单中的隐藏字段将与其他所有内容一起发送到服务器,并与其他字段一样绑定。

非常感谢,很抱歉让您困惑,但不管您的答案是什么,我都在寻找您的答案。