wix-incubator / accord

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

Validate Empty Json #112

Closed SrijeshKhanal closed 7 years ago

SrijeshKhanal commented 7 years ago

In Some case we need to validate Empty Json as well. For Example case class Test(p:Option[Int], n: Option[String], q: Option[Seq[String]])

val vt = validator[Test] { t => t.p is is notEmpty t.n is notEmpty t.q is notEmpty } The above example is to validate fields of json is provided or not But in some case we would like to validate whether Json provided is empty as well as above case . So How can this be done. For Example If we provide Following json it should also validate Empty Json { }

holograph commented 7 years ago

Let's see if I have it right: you want an instance to be valid if all are empty or none are empty?

import com.wix.accord._
import dsl._

case class Test(p:Option[Int], n: Option[String], q: Option[Seq[String]])

implicit val vt = validator[Test] { t => 
  ((t.p is empty) and (t.n is empty) and (t.q is empty)) or 
  ((t.p is notEmpty) and (t.n is notEmpty) and (t.q is notEmpty)) 
}

validate(Test(None, None, None))
// res0: com.wix.accord.Result = Success

validate(Test(Some(5), Some("asdf"), Some(Seq.empty)))
// res1: com.wix.accord.Result = Success

validate(Test(None, Some("asdf"), Some(Seq.empty)))
// res2: com.wix.accord.Result =
// Failure(Set(unknown with value "Test(None,Some(asf),Some(List()))" doesn't meet any of the requirements:
// |-- n with value "Some(asdf)" must be empty
// |-- p with value "None" must not be empty
// `-- q with value "Some(List())" must be empty))
holograph commented 7 years ago

@SrijeshKhanal does that answer your question?...

SrijeshKhanal commented 7 years ago

@holograph Yes It answer my question. Thanks for your help