wix-incubator / accord

Accord: A sane validation library for Scala
http://wix.github.io/accord/
Other
529 stars 55 forks source link

Can't use "if-else if-else" or "if-else" to verify multiple assertions when defining validator with DSL #157

Closed webblin034 closed 3 years ago

webblin034 commented 4 years ago

Official Document : " Accord supports several native Scala control structures, notably ifs and pattern matching " in http://wix.github.io/accord/dsl.html

Library Dependencies :

libraryDependencies ++= Seq(
  "com.wix"                   %% "accord-core"                 % "0.7.6" % Test,
  "org.scalatest"             %% "scalatest"                   % "3.2.2"  % Test
)

Input Data :

case class InputData(
  id: String,
  name: Option[String] = None,
  description: Option[String] = None,
  items: Seq[String] = Seq.empty
)

Unit Test :

      val data = InputData("", None, None, Seq.empty)
      val result = validate(data)
      result.isFailure shouldBe true
      result.toFailure.value.violations.size shouldBe 4

Test Failed Due To Only Checking Last Validation Rule !

  implicit val inputDataValidator: Validator[InputData] = validator[InputData] { request =>
    if (request.name.isDefined) {

    } else {
      request.id is notBlank 
      request.name.mkString is notBlank          
      request.description.mkString is notBlank 
      request.items is notEmpty // <=== Only Check Last Assertion
    }
    ()
  }
noam-almog commented 3 years ago

use this validator:

    implicit val inputDataValidator: Validator[InputData] = validator[InputData] { request =>
        request.id is notBlank
        request.name.each is notBlank
        request.description.each is notBlank
        request.items is notEmpty // <=== Only Check Last Assertion
    }