Add expected value to RuleViolation
frobs opened this issue · 1 comments
frobs commented
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