gpt4 book ai didi

forms - 重复值的唯一约束

转载 作者:行者123 更新时间:2023-12-04 19:12:54 42 4
gpt4 key购买 nike

我正在尝试 define a formplay! 2.0.4具有以下属性和约束:

  • 该表单处理重复值(让我们方便地假设这些值的类型是 number )。所以这会让我们得到这样的东西:
    "numbers" -> list(number)
  • 每个号码必须是唯一的,即它对于提交的所有其他号码必须是唯一的,并且对于数据库中已经存在的号码必须是唯一的(这可以通过一些函数 check(num: Int): Boolean 进行检查)。
  • 形式错误应该特定于数字,而不是唯一的。我不希望出现“有重复号码”的一般形式错误。

  • 最好的方法是什么?

    最佳答案

    这里的技巧是定义一个自定义 Constraint有点像这样 example .定制Constraint然后可以在 Mapping[T] 上使用使用 verifying 验证表单中的字段方法。

    定制Constraint包含返回 ValidationResult 的逻辑即 ValidInvalid .错误消息可以传递给 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)

    - 等等

    注意我定义了 numbers作为 String形式中。当我将其定义为 list(number)它一直评估到 List() .我认为这是一个具有约束力的问题。使用 List(1,2,3) 是一个相当简单的更改而不是 "1 2 3"如果使用 list(number)作品。

    - sample

    enter image description here
    enter image description here
    enter image description here

    关于forms - 重复值的唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432274/

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