Last active
December 13, 2016 21:21
-
-
Save erichonorez/53e699cb0213d71908ac23db02be1eb8 to your computer and use it in GitHub Desktop.
Validation with scalaz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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