Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to have a common rule for 2 validators? #10

Open
mii9000 opened this issue Mar 14, 2018 · 1 comment
Open

How to have a common rule for 2 validators? #10

mii9000 opened this issue Mar 14, 2018 · 1 comment
Labels

Comments

@mii9000
Copy link

mii9000 commented Mar 14, 2018

Maybe inherit from a base rule?
What I want is not to repeat the same rules in multiple validators.

@krzemin
Copy link
Owner

krzemin commented Mar 20, 2018

Hey, sure, it's possible with octopus.
I'm guessing you have some base trait and few case classes extending it.

sealed trait Person {
  def id: Int
  def name: String
}

case class Employee(id: Int, name: String, salary: Long) extends Person

case class Employer(id: Int, name: String, employees: List[Employee]) extends Person

Let's define validators for base trait and compose them with rules for case classes.

import octopus.dsl._

implicit val personValidator: Validator[Person] = Validator[Person]
  .rule(_.id > 0, "id must be greater than 0")
  .rule(_.name.trim.nonEmpty, "name must not be empty")

implicit val employeeValidator: Validator[Employee] = Validator[Employee]
  .composeSuper(personValidator)
  .rule(_.salary >= 10000, "salary must be at least 10000!")

implicit val employerValidator: Validator[Employer] = Validator[Employer]
  .composeSuper(personValidator) // employer is also a person, so it validate its id and name
  .composeDerived // composing derived validator for list of employees

See how they work.

import octopus.syntax._

val badEmployee = Employee(0, "", 500)

badEmployee.validate
// invalid:
//  : id must be greater than 0
//  : name must not be empty
//  : salary must be at least 10000!

val goodEmployee = Employee(3, "John", 15000)

goodEmployee.validate
// valid

val badEmployer = Employer(-5, "", List(badEmployee))

badEmployer.validate
// invalid:
//  : id must be greater than 0
//  : name must not be empty
//  employees[0]: id must be greater than 0
//  employees[0]: name must not be empty
//  employees[0]: salary must be at least 10000!

val goodEmployer = Employer(5, "Mike", List(goodEmployee))

goodEmployer.validate
// valid

Hope it helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants