konform-kt / konform

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

How to validate single values? #54

Closed amr closed 1 year ago

amr commented 1 year ago

For example, how to create a validation for a String or LocalDate? without having them part of some other object

I was able to achieve by dropping to addConstraint:

va validation = Validation<String?> {
    addConstraint("must be 4 digits") { it != null && it.length == 4 }
}

but wasn't unable to utilize required, ifPresent or any of the existing validators (minLength, ...etc).

Is that supported?

nlochschmidt commented 1 year ago

Just to be clear. You are asking specifically about validating nullable values like String? and LocalDate? correct?

Because non-nullables work, e.g.

val validatePassword = Validation<String> {
    minLength(8)
}

I believe it is currently not possible to validate nullable in a nice way. Good catch.

I guess we could do either something like

Validation<String?>.ifPresent {
    minLength(8)
}

Or probably better

Validation<String?> {
    ifPresent {
       minLength(8)
    }
}
amr commented 1 year ago

Yep that's accurate, both suggested versions look great to me