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;
}