Reputation: 97
For starters, I am new to Kotlin and have only been working with Android Studio for 2 weeks.
I'm just trying to check if the EditText field contains any digits/symbols/chars. I tried writing it like this:
if (editText!!.text.contains(Int)) {
textView?.text = "ERROR! EDITTEXT FIELD CONTAINS DIGITS!"
}
But it doesn't work like that. How can i check, if text is numeric or not, or maybe contains symbols (like "/?!:;%") for example? Thanks for your help!
Upvotes: 8
Views: 11332
Reputation: 1596
Uppercase letters:
if (yourString.contains("[A-Z]".toRegex())) {
//do something
}
Lowercase letters:
if (yourString.contains("[a-z]".toRegex())) {
//do something
}
Numbers:
if (yourString.contains("[0-9]".toRegex())) {
//do something
}
Special characters:
if (yourString.contains("[!\"#$%&'()*+,-./:;\\\\<=>?@\\[\\]^_`{|}~]".toRegex())) {
//do something
}
All above characters:
if (yourString.contains("[A-Za-z0-9!\"#$%&'()*+,-./:;\\\\<=>?@\\[\\]^_`{|}~]".toRegex())) {
//do something
}
Upvotes: 16
Reputation: 15183
Since you need to check if the text contains only letters or not, rather than using a regex for any digits/special characters, you can use a regex with a negation on letters [^A-Za-z]
, which would mean anything other than letters. So your logic would be
if (editText!!.text.contains(Regex("[^A-Za-z]"))) {
textView?.text = "ERROR! EDITTEXT FIELD CONTAINS DIGITS/SPECIAL CHARS!"
}
Note that this considers only the English letters.
Upvotes: 6
Reputation: 164099
Define a string that contains all the symbols and digits that you want to check:
val symbols = "0123456789/?!:;%"
and then use any
:
if (editText!!.text.any {it in symbols}) {
textView?.text = "ERROR! EDITTEXT FIELD CONTAINS DIGITS/INVALID SYMBOLS!"
}
Upvotes: 3