Skip to content

Instantly share code, notes, and snippets.

@seamusv
Created November 25, 2019 16:42
Show Gist options
  • Save seamusv/c7cd13704cb64de12975e8285b9443ef to your computer and use it in GitHub Desktop.
Save seamusv/c7cd13704cb64de12975e8285b9443ef to your computer and use it in GitHub Desktop.
package ca.yk.gov.cfs.fm.common
import scala.util.matching.Regex
object rules {
sealed trait ValidatorOp[A]
object ValidatorOp {
final case class Definition[A](fieldName: String, rules: RuleOp[A]) extends ValidatorOp[A]
}
sealed trait RuleOp[A] { self =>
def &&(that: RuleOp[A]): RuleOp[A] = RuleOp.AndRuleOp(self, that)
def ||(that: RuleOp[A]): RuleOp[A] = RuleOp.OrRuleOp(self, that)
}
object RuleOp {
final case class MaxLengthRuleOp(maxLength: Int) extends RuleOp[String]
final case object NonEmptyRuleOp extends RuleOp[String]
final case class RegexRuleOp(regex: Regex) extends RuleOp[String]
final case class StartsWithRuleOp(startsWith: String) extends RuleOp[String]
final case class AndRuleOp[A](left: RuleOp[A], right: RuleOp[A]) extends RuleOp[A]
final case class OrRuleOp[A](left: RuleOp[A], right: RuleOp[A]) extends RuleOp[A]
}
def define[A](fieldName: String, rules: RuleOp[A]): ValidatorOp[A] = ValidatorOp.Definition[A](fieldName, rules)
def maxLength(maxLength: Int): RuleOp[String] = RuleOp.MaxLengthRuleOp(maxLength)
def nonEmpty: RuleOp[String] = RuleOp.NonEmptyRuleOp
def pattern(regex: Regex): RuleOp[String] = RuleOp.RegexRuleOp(regex)
def startsWith(value: String): RuleOp[String] = RuleOp.StartsWithRuleOp(value)
sealed trait DomainErrors {
val field: String
}
final case class MaxLengthExceeded(field: String, maxLength: Int) extends DomainErrors
final case class NonEmptyRequired(field: String) extends DomainErrors
final case class PatternMismatch(field: String) extends DomainErrors
final case class StartsWithMismatch(field: String, startsWith: String) extends DomainErrors
}
object SampleValidator extends App {
import CatsValidated._
import rules._
val result: ValidationResult[String] = validate("YUKON", validators.organisationOp)
println(result)
println(validate(null, define("FOO", nonEmpty || startsWith("S"))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment