wix-incubator / accord

Accord: A sane validation library for Scala
http://wix.github.io/accord/
Other
530 stars 55 forks source link

Add expected value to RuleViolation #107

Closed frobs closed 7 years ago

frobs commented 7 years ago

Hello. I think that will be good add to RuleViolation class a field with the expected value. With this value we can set our custom error messages:

//our applicationErrorCodes
object Code extends Enumeration {
    type ErrorCodes = String
    val greaterOrEqual = "number.mustBe.greaterOrEqual"
  }

//Our messages, maybe internationaliced maybe not
  val message: Map[String, String] = Map(
    Code.greaterOrEqual -> "Number %s must be greater than or equal to %s",
  )

//our validator
val oneValidator = validator[ObjectToBeValidated] { element =>
    element.quantity as Code.greaterOrEqual should be >= 0.0
  }

private def getValidationError(ruleViolation: RuleViolation): ValidationError = {
    val code = Descriptions.render(ruleViolation.description)
    ValidationError(code = code, message = String.format(ValidationError.message(code), ruleViolation.value.toString(),ruleViolation.expectedValue.toString()), receivedValue = ruleViolation.value.toString, expectedValue = ruleViolation.expectedValue)
  }

private def toErrorSeq(errors: Failure): Seq[ValidationError] = {
    errors.violations.map(error => {
      error match {
        case error: RuleViolation => errors :+= getValidationError(error)
      }
    })
  }

val validationResult = validate(objectToBeValidated)(oneValidator)
if(validationResult.isFailure){
toErrorSeq(result.asInstanceOf[Failure])
}

This is a simplified example but this is the idea

holograph commented 7 years ago

This is essentially the same as #21, which I expect to give full attention to in the next few weeks as part of 0.7. I'm still trying to get a clean API out of the whole thing, but you can weigh in (and/or track progress) in that issue.