bananana
bananana

Reputation: 105

how to check if string contains only numerics or letters properly? Android

I am trying to set requirements for a certain number that a user requiers to enter(pNumber). pNumber should consist of 2 letters then 6 letters or numbers and finally a number.

I have implemented a method i found here on stackoverflow, but when i enter a number like: "LL^&%JJk9" it still gives me a positive result? to my understanding .matches checks that a string only consists of the given values?

String First = pNumber.substring(0, 2);
String Middle = pNumber.substring(2, 8);
String Last = pNumber.substring(8, 9);

if (First.matches(".*[a-zA-Z].*") && Middle.matches(".*[a-zA-Z0-9].*") && Last.matches(".*[0-9].*")) {
  greenOk.setVisibility(View.VISIBLE);
  nextBtn.setEnabled(true);
} else {
  redCross.setVisibility(View.VISIBLE);
}

Upvotes: 1

Views: 2670

Answers (4)

Faizan Haidar Khan
Faizan Haidar Khan

Reputation: 1215

TextUtils class has various methods and one of them is given below.

TextUtils.isDigitsOnly(string)

Upvotes: 0

Knossos
Knossos

Reputation: 16038

This Stackoverflow details how to use Apache Commons to solve your problem.

If you are looking for a Regular Expression route of solving your issue, this will likely help you:

if(pNumber.matches("[a-zA-Z]{2}[a-zA-Z0-9]{6}[0-9]")) {
    greenOk.setVisibility(View.VISIBLE);
    nextBtn.setEnabled(true);
} else {
    redCross.setVisibility(View.VISIBLE);
}

Upvotes: -1

Leifb
Leifb

Reputation: 380

You could use Apache Commons Lang for that. There you have methods like isNumeric and isAlphanumeric

Or use methods like Character isDigit

Upvotes: 1

R.Costa
R.Costa

Reputation: 1393

Maybe something like:

    String input1 = "TYe4r5t12";
    String input2 = "LL^&%JJk9";

    String pattern = "([a-zA-Z]{2}[a-zA-Z0-9]{6}[0-9]{1})";

    Pattern r = Pattern.compile(pattern);

    Matcher m = r.matcher(input1);

    if (m.find()) {
        System.out.println("Valid !!!");
    }else{
        System.out.println("Invalid !!!");
    }

Upvotes: 1

Related Questions