'how to check not Digit Only android studio? [duplicate]
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.
Solution 1:[1]
You can use Regex:
if ("[0-9]+".toRegex().matches(YOUR_STRING)) {
// Only digits
}
Change YOUR_STRING to the string you wish to check.
Solution 2:[2]
You can use regex pattern and match,
val regexStr = "^[0-9]*$";
if(yourid.text.toString().trim().matches(regexStr))
{
//contains only numbers
}
else{
//contains other types too
}
This will be helpful when you are trying to validate only numbers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gioravered |
| Solution 2 | Mathi Vanan |
