octopus icon indicating copy to clipboard operation
octopus copied to clipboard

How to include the value in the error string?

Open mii9000 opened this issue 6 years ago • 3 comments

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")

mii9000 avatar Mar 26 '18 05:03 mii9000

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 avatar Mar 26 '18 08:03 krzemin

@krzemin I will work on this as soon as I am able

mii9000 avatar Mar 27 '18 04:03 mii9000

@krzemin Sounds like ^^ was something you were interested in adding? Is this library not really maintained anymore?

andyczerwonka avatar Jun 05 '20 12:06 andyczerwonka