12
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?

2 Answers 2

13

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.

1
  • 3
    Thank you for your answer and for pointing to the location of the existing bug report. That bug was created in Jan 2012. Wow. Mar 26, 2018 at 23:09
2

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
1
  • 2
    It's a good idea to add Kotlin code here. I also did, but using a different approach. +1 Sep 22, 2020 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.