使用Scala Cats验证多个ADT



我正在尝试验证scala中的配置。首先,我将config-json转换为相应的case类,然后对其进行验证。由于我想缓慢失败,我收集所有失败的验证,而不是在第一次验证失败后返回。我计划使用cats库cats验证提供的应用函子。

我面临的问题是链接中显示的表单验证适用于简单案例类

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)

在这种情况下,字段"username"的验证独立于字段"firstName"的验证。但是如果

  1. 我不得不对"firstName"one_answers"userName"进行某种验证(假设两个的Levenstein距离应该是<=某个数字)
  2. case类不是由简单的基元(Int,String)组成的,而是由其他case类作为其成员。如上文所述的用户案例类

一般来说,应用函子的方法适用于这种情况吗?我是否应该收集所有失败的验证?

附言:如果有什么不正确的地方请原谅,我是scala的新手。

基于cats验证示例

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

检查这个小提琴

只有当元组(ValidationResult[_], ValidationResult[_], ...)中的数据是Valid时,才调用mapN的函数。如果元组中的一个或多个元素是Invalid,则将它们收集到NotEmtpyChain中。

总之,调用了所有的validate方法,当所有方法返回Valid[_]时,将应用mapN函数。

相关内容

  • 没有找到相关文章

最新更新