2

Like if the user inputs only letters it will complain that the username must contain numbers and when the user inputs only numbers it will complain that username must contain letters.

Here's my code, but it doesn't work properly.

if(!username.matches("[a-zA-Z0-9]+")){
    Toast.makeText(this, "Username must be alphanumeric", Toast.LENGTH_SHORT).show();
    return;
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
  • 1
    Does this answer your question? [Validation allow only number and characters in edit text in android](https://stackoverflow.com/questions/14192199/validation-allow-only-number-and-characters-in-edit-text-in-android) – Josh Correia Jul 17 '20 at 20:15

2 Answers2

7

you can just check for them separately after the main check

if(!username.matches("[a-zA-Z0-9]+")){
    Toast.makeText(this, "Username must be alphanumeric", Toast.LENGTH_SHORT).show();
    return;
}

if(!username.matches("^.*[0-9].*$")){
    Toast.makeText(this, "it should contain numbers", Toast.LENGTH_SHORT).show();
    return;
}

if(!username.matches("^.*[a-zA-Z].*$")){
    Toast.makeText(this, "it should contain letters", Toast.LENGTH_SHORT).show();
    return;
}

EDIT:

To break down the regex:

^.*[0-9].*$ --> ^ <-- start of String

$ <-- end of String

.* match any (can also match empty string)

[0-9] match a number

you can also replace .* with [a-zA-Z0-9]* however, the first check will take care of that so its not really necessary.

EDIT 2

Another Approach is to check if it only contains letter or number: I prefer this one as its much more simplified, however it is essential to do the first check

if(!username.matches("[a-zA-Z0-9]+")){
    Toast.makeText(this, "Username must be alphanumeric", Toast.LENGTH_SHORT).show();
    return;
} 

if(username.matches("[a-zA-Z]+")){  // only contains letters
    Toast.makeText(this, "it should contain numbers", Toast.LENGTH_SHORT).show();
    return;
}

if(username.matches("[0-9]+")){ //only contains numbers
    Toast.makeText(this, "it should contain letters", Toast.LENGTH_SHORT).show();
    return;
}
nafas
  • 5,283
  • 3
  • 29
  • 57
1

try this user Editext property android:digits so you can restrict user to enter only allowed charecter

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:digits="ABCDEFGHIJKLMNOPQRSTUVWX1Z1234567890abcdefghijklmnopqrstuvwxyz "/>
AskNilesh
  • 67,701
  • 16
  • 123
  • 163