Android Question test a variable/string for numbers only?

techknight

Well-Known Member
Licensed User
Longtime User
Is there a way to check a variable/string if it has characters with anything other than numbers?

Reason I ask, I have an edit text control that only expects numbers and dashes "-" and if you fatfinger, or purposely type characters in the box, itll crash the app as I am dealing with it numerically.

Of course, I strip the "-" out of the variable before processing it as a number.

any ideas? thanks.
 

klaus

Expert
Licensed User
Longtime User
You could also limit the characters the user can enter.
With
EditText1.InputType = EditText1.INPUT_TYPE_NUMBERS
or
EditText1.InputType = EditText1.INPUT_TYPE_DECIMAL_NUMBERS

You can also have a look at the IME library which allows to define specific limitations.
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
I ended up doing it this way:

B4X:
    If varRegKey = "" Then Return False
    varRegKey = varRegKey.Replace("-", "")
    varRegKey = varRegKey.Replace(" ", "")
    Matcher1 = Regex.Matcher("\d+", varRegKey)
    Do While Matcher1.Find
          Matchcount = Len(Matcher1.Match)
    Loop
    If Matchcount <> Len(varRegKey) Then Return False

Which worked perfectly, since anything other than numbers in the editbox will increase its length and wont get matched = return false.
 
Upvote 0
Top