Compose validators
You can easily compose own validator using defined already validators. For example:
import pl.muninn.simple.validation._
case class Field(name:String, otherField:String)
val myValidString = notEmptyString and minimalLengthString(8)
// myValidString: cats.data.NonEmptyList[validator.ValueValidator[String]] = NonEmptyList(
// head = pl.muninn.simple.validation.validator.ValueValidator$$anon$1@282aff6c,
// tail = List(
// pl.muninn.simple.validation.validator.ValueValidator$$anon$1@41912f76
// )
// )
val schema:ValidationSchema[Field] = createSchema { context =>
context.field(_.name).is(myValidString) +
context.field(_.otherField).is(myValidString)
}
// schema: ValidationSchema[Field] = <function1>
schema.validate(Field("",""))
// res0: ValidationResult = Invalid(
// e = Append(
// leftNE = Append(
// leftNE = Singleton(a = EmptyField(field = "name")),
// rightNE = Singleton(
// a = MinimalLength(field = "name", expected = 8, value = 0)
// )
// ),
// rightNE = Append(
// leftNE = Singleton(a = EmptyField(field = "otherField")),
// rightNE = Singleton(
// a = MinimalLength(field = "otherField", expected = 8, value = 0)
// )
// )
// )
// )
Use schema as validators
You can easily use existing schema as validator for field. For example:
import pl.muninn.simple.validation._
case class InputValue(name:String)
val inputSchema:ValidationSchema[InputValue] = createSchema { context =>
context.field(_.name).notEmpty
}
// inputSchema: ValidationSchema[InputValue] = <function1>
case class RequestClass(input:InputValue)
val requestSchema:ValidationSchema[RequestClass] = createSchema { context =>
context.field(_.input).is(inputSchema)
}
// requestSchema: ValidationSchema[RequestClass] = <function1>
requestSchema.validate(RequestClass(InputValue("")))
// res1: ValidationResult = Invalid(
// e = Singleton(a = EmptyField(field = "input.name"))
// )