android.text.TextUtils.isDigitsOnly("")
I'm using above code to check input string is a valid number or not but isDigitOnly()
function return true
for empty string.
How to make it to return false
for empty string or there is other Android build in function?
As Selvin mentioned correctly this is actually a bug that persists until today. See here.
You can get around that by doing this:
Java
boolean myIsDigitsOnly(String str) {
return str.isEmpty() && TextUtils.isDigitsOnly(str);
}
Now you call your own custom method:
myIsDigitsOnly(""); // returns false
Kotlin
In Kotlin, you don't need TextUtils
at all. Just create your own extension function like this:
fun String.isDigitsOnly() = all(Char::isDigit) && isNotEmpty()
Try it out here!
Thanks to silwar who inspired me to make the Java one more concise.
For Kotlin Users
Although its an old question with accepted answer, this is suggestion to improve this answer in Kotlin language by following code
fun String.myIsDigitsOnly(): Boolean {
return TextUtils.isDigitsOnly(this) && this.isNotEmpty()
}
Now you can call your method like
"".myIsDigitsOnly() // returns false
or
"123523423".myIsDigitsOnly() // returns false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With