Skip to content

Instantly share code, notes, and snippets.

@erichonorez
Last active December 13, 2016 21:21
Show Gist options
  • Save erichonorez/53e699cb0213d71908ac23db02be1eb8 to your computer and use it in GitHub Desktop.
Save erichonorez/53e699cb0213d71908ac23db02be1eb8 to your computer and use it in GitHub Desktop.
Validation with scalaz
// Start writing your ScalaFiddle code here
import scalaz._
import Scalaz._
case class LoanApplication(
val firstName: String,
val lastName: String,
val nationalRegister: String,
val emailAddress: Option[String]
)
type Valid[A] = ValidationNel[String, A]
def validateFirstName(firstName: String): Valid[String] = {
val length = firstName.length
if (length < 24 && length > 0) firstName.successNel[String] else "error".failureNel[String]
}
def validateLastName(lastName: String): Valid[String] = {
val length = lastName.length
if (length < 48 && length > 0) lastName.successNel[String] else "error".failureNel[String]
}
def validateNationalRegister(nationalRegister: String): Valid[String] = {
val length = nationalRegister.length
if (length == 11) nationalRegister.successNel[String] else "error".failureNel[String]
}
def validateAll(firstName: String, lastName: String, nationalRegister: String, emailAddressO: Option[String]): Valid[LoanApplication] = {
(
validateFirstName(firstName) |@|
validateLastName(lastName) |@|
validateNationalRegister(nationalRegister)
) { LoanApplication(_, _, _, None) }
}
def validateAll2(firstName: String, lastName: String, nationalRegister: String, emailAddressO: Option[String]): Valid[LoanApplication] = {
(
validateFirstName(firstName) |@|
validateLastName(lastName) |@|
validateNationalRegister(nationalRegister)
) { (f, l, n) => LoanApplication(f, l, n, None) }
}
println(
validateAll("Eric", "Honorez", "87102139103", None)
)
println(
validateAll("", "Honorez", "87102139103", None)
)
println(
validateAll2("", "Honorez", "87102139103", None)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment