Jakarta Bean Validation 3.0 for Scala.
3.x
and 2.13.x
, Java 11
and aboveOption
, Seq
, Set
, Map
, Vector
, etcAdd the following to build.sbt
:
libraryDependencies ++= Seq(
"org.bitlap" %% "validation-scala-core" % "latest version"
)
Step 1. Add annotations to your case class:
import jakarta.validation.constraints.Size
case class Person(
// @(Size @getter)(min = 4) also supports the getter method
@(Size @field)(min = 4)
name: Option[String]
)
Step 2. Create validator by our library:
import bitlap.validation.ScalaValidatorFactory
import bitlap.validation.ScalaClockProvider
val validator = ScalaValidatorFactory.scalaValidator(new ScalaClockProvider)
Step 3. Validate a case class object:
val obj = Person(Some("abc"))
val violations = validator.validate(obj)
if (violations.nonEmpty) {
println("Violations found!")
}
This allows us to use it like SpringBoot. It does not support annotations with group parameters and only supports scala 3!
Add the following to build.sbt
:
libraryDependencies ++= Seq(
"org.bitlap" %% "validation-scala-core" % "latest version",
// "org.bitlap" %% "validation-scala-ext" % "latest version", // for zio
)
autoCompilerPlugins := true
addCompilerPlugin("org.bitlap" %% "validation-scala-plugin" % "latest version")
Then, checking code will be automatically inserted during compilation and may throw an IllegalArgumentException
if the constraint checking fails.
If you do not wish to throw an exception directly, you should add a bind: BindingResult
parameter to method:
import jakarta.validation.Valid
import jakarta.validation.constraints.NotNull
def validatedTwoParams(@Valid person1: Person, @Valid person2: Person): String
def validatedOneParams(@Valid person1: Person): String
// The plugin captures the `bind` parameters based on the type, so the name doesn't matter.
def validatedBindParams(@Valid person1: Person, bindingError: BindingResult = BindingResult.default): String
def validatedNotNullParams(@Valid @NotNull person1: Person): String
import jakarta.validation.constraints.{ NotBlank, NotNull }
def validatedNotNullParams(@NotNull person1: Person): String
def validatedNotEmptyParam(@NotBlank name: String): String
bean-validation-scala, JSR 303 and 349 Bean Validation for Scala.