konform-kt / konform

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

Feature request: ability to validate string as a number. #23

Closed davidmoshal closed 3 years ago

davidmoshal commented 3 years ago

Given: an HTTP request with a string parameter representing a number. (btw, this is all HTTP requests as all parameters are strings, or arrays of strings!)

Then: I'd like to be able to validate that this string represents a number, and validate that number.

For example, given a request which posts a user's age, eg: "56".
I'd like to validate that the string is a number, and that it's a positive integer.

I imagine that this could be provided as ifNumber, in the same way as isPresent.

eg:

UserProfile::age ifNumber {
    minimum(0)
}
nlochschmidt commented 3 years ago

Hey, this is too specific to be included directly in konform.

However if it's a simple check for age and you are fine with allowing up to 199 you could do a regex based check

data class Person(val age: String)
val validation = Validation<Person> {
    Person::
        pattern("1{0,1}\\d{1,2}")
    }
}

Or you could also write a simple matcher:

fun ValidationBuilder<String>.inRange(range: IntRange): Constraint<String> {
    return addConstraint("number must be in range {0}", range.toString()) { 
        it.toIntOrNull() in range 
    }
}

and use it like this:

val validation = Validation<Person> {
    Person::age {
        inRange(0..199)
    }
}