Guidance to a Scalaz newbie starting with Validation

45 views
Skip to first unread message

chrsan

unread,
Feb 23, 2012, 3:15:21 PM2/23/12
to scalaz
Hi!

I've been wanting to check out Scalaz for quite some time now but
never really had the chance to do so. Now I have a case where I need
some validation logic and thought that this must be a perfect
opportunity to scratch the surface of Scalaz. Sorry if this question
have been asked a 1000 times, but I need a jump start to get it going.

I've been using the query param logic in Unfiltered for validation and
will use this as an easy example to try to illustrate what I want to
do. Let's say I have a Map[String, String] and that I want to check
some keys and its values. I want to be able to do multiple validation
tests per value with errors accumulated. Like this:

case class Foobar(foo: Int, bar: Option[String])

val expected = for {
foo <- lookup("foo") is
required("is missing") is
nonempty("is empty") is
int(n => n + " is not an int") is
pred(n => n < 10, _ => "Number must be less than 10")
bar <- lookup("bar") is
is optional is trimmed
} yield Foobar(foo.get, bar.get)

expected(data) match {
case Right(foobar) => // Succesful validation
case Left(log) => // log = List of failures
}

In Unfiltered a validation tests short curcuit on first error. I.e.
for foo nonempty will not be done if required failed.

I would also be able to compose validations. Maybe I need to do the
check for foo in multiple contexts.

Thanks in advance,
Christer

Diego Medina

unread,
Feb 23, 2012, 8:47:25 PM2/23/12
to sca...@googlegroups.com
This is one of the best examples I have found so far showing validation
https://gist.github.com/970717

hope it helps

Diego

> --
> You received this message because you are subscribed to the Google Groups "scalaz" group.
> To post to this group, send email to sca...@googlegroups.com.
> To unsubscribe from this group, send email to scalaz+un...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/scalaz?hl=en.
>

--
Diego Medina
Lift/Scala Developer
di...@fmpwizard.com
http://www.fmpwizard.com

Christer Sandberg

unread,
Feb 24, 2012, 1:28:06 AM2/24/12
to sca...@googlegroups.com
Great! Thanks a lot. Will check it out right away.

/Christer
Reply all
Reply to author
Forward
0 new messages