konform-kt / konform

Portable validations for Kotlin
https://www.konform.io
MIT License
651 stars 39 forks source link

How to add a custom property to validations? #48

Open gonzalo-rodriguez opened 2 years ago

gonzalo-rodriguez commented 2 years ago

Maybe this is out of the scope of the library (apologies if it is), but... is there a way to add a custom property to validations?

For instance, I would like to add a severity property, but in order to do that it would have to be part of both Validation and ValidationResult (so that I can see the severity of the validations that have failed), and I cannot seem to find a way to do that.

Thanks in advance, and keep up the great work!

nlochschmidt commented 2 years ago

Thanks! Sounds interesting!

I am uncertain how opinionated konform should be about severity. Not sure what needs others might have around this.

Especially wondering about the number and names of severity levels and also whether the severity filter should be applied during validation or after e.g. to allow a validation that only had warnings to still yield Valid when there are no errors.

One idea is to add untyped user attributes to validations. Essentially adding a Map<String, Any>. However then the filter couldn't be applied during validation, and also the severity value would need casting when retrieving it. Not really fond of this idea.

@gonzalo-rodriguez Maybe you can provide a code example for how you would wish this to look like?

gonzalo-rodriguez commented 2 years ago

Thank you, @nlochschmidt!

To be honest, for my particular use case, I think I like the Map<String, Any> idea better. It has its own drawbacks, but it's the option that gives the most flexibility, especially because it would work for other properties, not just for severity.

Also, as you said, needs around severity might vary, and trying to accomodate all possible cases within konform might be too tricky (different levels and names for them, whether to actually add some logic for it inside konform or let users do whatever they want after the validation...)

I'm afraid I'm not familiar enough with the konform code to actually propose a solution, but it might make sense to have it work in a way similar to how constraints work in ValidationBuilder: have something like private val properties : Map<String, Any> there, and then add the same property to ValidationResult, and just copy the map from the validation to the result in the validate function.

What do you think?

dhoepelman commented 3 months ago

I'm not completely opposed to the idea, but I don't think it's a priority right now. The way I would go about this is to make it easier to "parse" the validation result, e.g. get the paths in a more structured way.

For now, for people wanting to do this I would recommend to have an additional thing looking at the ValidationResult's datapaths and basing the severity on that.