octopus
octopus copied to clipboard
How to include the value in the error string?
If the rule()
would have another overload that takes a lambda then this would work. Much like FluentValidations for .NET
val personValidator: AsyncValidator[Person] =
AsyncValidator[Person]
.async.rule(_.id, validateId, (p: Person) => s"${p.Id} does not exist")
Currently there is no direct support for constructing error messages based on validated entities values. I think it may be a good idea for a feature 👍
In terms of existing combinators, you may want to bend a ruleEither
a bit:
val personValidator: AsyncValidator[Person] =
AsyncValidator[Person]
.async.ruleEither((p: Person) => validateId(p.id).map(isValid => if(isValid) Right(true) else Left(s"${p.Id} does not exist")), "<not used>")
It's not such elegant as direct support, but should work as you intended. The only difference would be that error message wouldn't be pointed specifically to .id
field, but to whole Person
entity.
Alternatively, you can re-model your Person
making id
a value class, like:
case class PersonId(value: Int) extends AnyVal // Int, String, UUID or whatever id type you're using
case class Person(id: PersonId, ...)
implicit personIdValidator: AsyncValidator[PersonId] = AsyncValidator[PersonId]
.async.ruleEither(validateId(_: PersonId).map(if(_) Right(true) else Left(s"${p.Id} does not exist")), "<not used>")
which points eventual validation error back to .id
field.
However I agree support for .rule(_.id, validateId, (p: Person) => s"${p.Id} does not exist")
would be more appropriate.
@krzemin I will work on this as soon as I am able
@krzemin Sounds like ^^ was something you were interested in adding? Is this library not really maintained anymore?