I'm working on a Kotlin function that needs to validate some data before making an API call. Part of that validation is verifying that an incoming parameter string represents a valid non-negative integer. My initial thought was to use String.toInt() and catch the NumberFormatException. Something like:
data class Foo(val port_range_from: String?)
{
init{
try{
require( port_range_from != null && port_range_from.toInt() > -1)
{
"port_range_from must be non-negative integer."
}
}
catch (e:NumberFormatException)
{
throw IllegalArgumentException("port_range_from must be non-negative integer.")
}
}
}
While this works for most inputs, there is a corner case. String.toInt() will strip off leading zeros and return the integer value with no exceptions. The API I am calling however, treats strings with leading zeros as invalid and will throw an error if I pass in such a value. So a value like "012" will pass my validation but will cause an error if passed to the API.
Is there a 'kotlin' way to detect Strings with leading zeros without having to manually parse through the string to find them myself?
Update:
I eventually settled on using a Regex to check the input String. I'm still not sure if this is the best solution.
require( Regex("^0$|^[1-9]+[0-9]*$").matches(port_range_from))
{
"port_range_from must be non-negative integer."
}
It's acceptable to use a regex like you mentioned, it's a common technique for input validation. But if, for any reason, you are looking for a non-regex alternative for this specific situation, you should also be able to go with this:
Converting the int back to a string and comparing it to the original string, is what makes sure there are no leading zeros.
In my opinion, in terms of readability, the regex does a better job.