Jakarta Bean Validation 3.0 for Scala.
- Support Scala
3.x
and2.13.x
, Java11
and above - Support validate scala types, e.g.
Option
,Seq
,Set
,Map
,Vector
, etc - Support validate object
- Support cascade validation
- For Scala3, support for parameter validation, catching errors and allowing access to error
Add 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
- Only instance methods of classes are supported due to the limitations of jakarta
- Overloading methods with the same number of parameters are not supported.
bean-validation-scala, JSR 303 and 349 Bean Validation for Scala.