Home > Mobile >  how to check not Digit Only android studio?
how to check not Digit Only android studio?

Time:03-01

I need to show an error if inputs in edit Text are any thing except numbers. I tried this code but it seems incorrect and does not work.

if(!EditText.text.isDigitsOnly()){
      EditText.error = "myError"
   }

I know about android:inputType="number" but I should not use it. I can use a loop to check it myself but I need a much cleaner way.

CodePudding user response:

You can use Regex:

if ("[0-9] ".toRegex().matches(YOUR_STRING)) {
    // Only digits
}

Change YOUR_STRING to the string you wish to check.

CodePudding user response:

I have created some functions hope it helps you

fun String?.hasOnlyDigits() : Boolean = try {
if (this.isNullOrEmpty())
    false
else Pattern.matches("[0-9] ", this)
} catch (e: Exception) {
    e.printStackTrace()
    false
}

fun String.isInt() : Boolean = try {
this.toIntOrNull() != null
} catch (e: Exception) {
   e.printStackTrace()
   false
}

    fun String.isDouble() : Boolean = try {
    this.toDoubleOrNull() != null
} catch (e: Exception) {
    e.printStackTrace()
    false
}

and you can use it as following

    if(!editText.text?.toString().hasOnlyDigits()){
       editText.error = "myError"
    }
  • Related