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

Question: Is it possible to access the validated property's value in the custom messages? #75

Open
nirsaadi opened this issue Aug 5, 2022 · 1 comment

Comments

@nirsaadi
Copy link

nirsaadi commented Aug 5, 2022

I was wondering if it's possible to access the validated property's value when creating custom messages files.
For example, imagine an address entity

data class Address(
    val street: String,
    val state: String,
    val zipcode: String
)

In addition, I created a custom validation that checks that the zipcode is of a given length (user provided):

data class IsOfLength(val allowedLength: Int?) : Constraint

fun <E, T> Validator<E>.Property<T?>.isOfLength(allowedLength: Int?) = this.validate(IsOfLength(allowedLength)) { it.length == allowedLength }

And finally my messages_en.properties file:

com.myProject.constraints.IsOfLength.message=zipcode {propertyValue} must be of length {allowedLength}

Now when I validate the address:

val myAddress = Address("street", "NY", "12345")

validate(entity){
    validate(Address::zipcode).isOfLength(5)
}

The message I would want to see is:
zipcode 12345 must be of length 5
However, propertyValue is obviously not part of the constraint params.

My question is, did I miss something and we can easily access it in our custom message file, or the only way to do it is to pass the property value directly to the constraint and use it like that.
e.g.

IsOfLength(val propertyValue: String, val allowedLength: Int?)

This would work but we have tons of validations and making a change to all of them to add the property value is cumbersome.

An alternative approach is to just format the message text upon handling the errors in the ValidationExceptionHandler class.
Since I can access the Constraint.value in the handle function there, I could inject the value directly in the Constraint.message using a simple string format.
It's significantly better than updating all the validations we already have, but I lose the custom formatters functionality valiktor provides by doing it, and it is still something I'd like to avoid if such functionality already exists and I just missed it.

Thanks in advance!

@arthur-rs
Copy link

I have the same problem, still can't solve it.

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

No branches or pull requests

2 participants