forms – 重复值的唯一约束
发布时间:2020-12-16 18:15:45 所属栏目:安全 来源:网络整理
导读:我在 play! 2.0.4尝试 define a form具有以下属性和约束: 表单处理重复值(可以方便地假设这些值的类型为数字).所以这将使我们得到这样的东西: "numbers" - list(number) 每个数字必须是唯一的,即它对于提交的所有其他数字必须是唯一的,并且它必须对数据库
我在
play! 2.0.4尝试
define a form具有以下属性和约束:
>表单处理重复值(可以方便地假设这些值的类型为数字).所以这将使我们得到这样的东西: "numbers" -> list(number) >每个数字必须是唯一的,即它对于提交的所有其他数字必须是唯一的,并且它必须对数据库中已存在的数字是唯一的(这可以通过某些函数检查(num:Int)来检查:布尔). 什么是最好的方式去? 解决方法
这里的技巧是定义类似于此
example的自定义约束类型.然后可以在Mapping [T]上使用自定义约束来使用验证方法验证表单中的字段.
自定义约束包含返回ValidationResult的逻辑,该ValidationResult是Valid或Invalid.可以将错误消息传递给无效结果,您可以在该结果中指定数据库中重复或存在的内容. 有关自定义验证的部分,请参见Play for Scala. – 创建约束 //Make this lazy to prevent java.lang.ExceptionInInitializerError at runtime. lazy val uniqueNumbersConstraint = Constraint[String](Some("Unique numbers constraint"),"")(checkNumbers) //"Business Logic". //Important part here is that the function returns a ValidationResult and complies with the signature for Constraint. i.e. f: (T) => ValidationResult //Return Valid if n in numbers is not in database and there are no duplicates. //Otherwise return Invalid and an error message showing what numbers are in the database or duplicated. def checkNumbers(numbers: String):ValidationResult = { val splitNums = numbers.split(" ").toList.map(_.toInt) val dbnums = splitNums.partition(database.contains(_)) if(dbnums._1.isEmpty && uniquesAndDuplicates(splitNums)._2.isEmpty){ Valid }else{ val duplicates = uniquesAndDuplicates(dbnums._2)._2 val error = "Database contains: " + dbnums._1 + ",duplicated values: " + duplicates Invalid(error) } } – 使用自定义约束验证表单 val helloForm = Form( tuple( "numbers" -> nonEmptyText.verifying(uniqueNumbersConstraint) )) – 公用事业 //Return unique values on left side and duplicate values on right side def uniquesAndDuplicates(numbers: List[Int]):Tuple2[List[Int],List[Int]] = { numbers.partition(i => numbers.indexOf (i) == numbers.lastIndexOf(i)) } def checkNum(num: Int) = { database.contains(num) } val database = List(5,6,7) – 等等 注意我在表单中将数字定义为字符串.当我将其定义为列表(数字)时,它会继续评估List().我认为这是一个具有约束力的问题.如果使用list(number)工作,使用List(1,2,3)而不是“1 2 3”是一个相当简单的更改. – 样品 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容