我正在尝试验证Scala中的配置。首先,我将config json转换为相应的case类,然后对其进行验证。因为我想慢慢失败,所以我收集所有失败的验证,而不是在第一个失败的验证后返回。我计划使用cats库Cats validation提供的适用函子。
我面临的问题是链接中显示的表单验证适用于简单案例类
final case class RegistrationData(username: String, password: String, firstName: String, lastName: String, age: Int)
// Below is the code snippet for applying validation from the link itself
{
(validateUserName(username),
validatePassword(password),
validateFirstName(firstName),
validateLastName(lastName),
validateAge(age)).mapN(RegistrationData)}
// A more complex case for validations
final case class User(name:String,adds:List[Addresses])
final case class Address(street:String,lds:List[LandMark])
final case class LandMark(wellKnown:Boolean,street:String)
在这种情况下,对字段“用户名”的验证独立于对“名字”的验证。但是如果
一般而言,适用函子的方法是否适合这种情况?我什至应该收集所有失败的验证吗?
PS:请原谅我,如果我提到的内容不正确,我是scala的新手。
答案 0 :(得分:1)
基于猫的验证示例
import cats.data._
import cats.data.Validated._
import cats.implicits._
final case class RegistrationData(name: Name, age: Int, workAge: Int)
final case class Name(firstName: String, lastName: String)
sealed trait DomainValidation {
def errorMessage: String
}
case object FirstNameHasSpecialCharacters extends DomainValidation {
def errorMessage: String =
"First name cannot contain spaces, numbers or special characters."
}
case object LastNameHasSpecialCharacters extends DomainValidation {
def errorMessage: String =
"Last name cannot contain spaces, numbers or special characters."
}
case object AgeIsInvalid extends DomainValidation {
def errorMessage: String =
"You must be aged 18 and not older than 75 to use our services."
}
case object AgeIsLessThanWorkInvalid extends DomainValidation {
def errorMessage: String =
"You must be aged 18 and not older than 75 to use our services."
}
sealed trait FormValidatorNec {
type ValidationResult[A] = ValidatedNec[DomainValidation, A]
private def validateFirstName(firstName: String): ValidationResult[String] =
if (firstName.matches("^[a-zA-Z]+$")) firstName.validNec
else FirstNameHasSpecialCharacters.invalidNec
private def validateLastName(lastName: String): ValidationResult[String] =
if (lastName.matches("^[a-zA-Z]+$")) lastName.validNec
else LastNameHasSpecialCharacters.invalidNec
private def validateAge(age: Int,
workAge: Int): ValidationResult[(Int, Int)] = {
if (age >= 18 && age <= 75 && workAge >= 0)
if (age > workAge)
(age, workAge).validNec
else
AgeIsLessThanWorkInvalid.invalidNec
else
AgeIsInvalid.invalidNec
}
def validateForm(firstName: String,
lastName: String,
age: Int,
workAge: Int): ValidationResult[RegistrationData] = {
(
(validateFirstName(firstName), validateLastName(lastName)).mapN(Name),
validateAge(age, workAge)
).mapN {
case (n, (a, w)) => RegistrationData(name = n, age = a, workAge = w)
}
}
}
object FormValidatorNec extends FormValidatorNec
println(FormValidatorNec.validateForm("firstname", "lastname", 40, 30))
println(FormValidatorNec.validateForm("firs2tname", "lastname", 20, 30))
选中此fiddle
仅当元组mapN
中的数据为(ValidationResult[_], ValidationResult[_], ...)
时才调用Valid
的功能。如果元组中的一个或多个元素为Invalid
,则将它们收集到NotEmtpyChain
中。
总而言之,所有validate
方法都被调用,并且当它们全部返回Valid[_]
时,将应用mapN
函数。