开发者

An else if statement for unwanted characters and too short a length of characters for edittext

I have an edittext variable named getusername I wish to use in an if statement.

I wish to check for unwanted characters like !,@,#,$,%,^,&,*,(,),etc. I also want to make sure the text from edittext will not be less than 3 characters.

Right now i'm using getusername.getText().toString() to get the values in edittext but I want to use an if statement that toasts "success" if the characters in the edittext match my exceptions. and if not toasts what the problem is.

Is there anyway to do this?

My current code asterisks mark where i need help on with my comments.

if (getusername.getText().toString() *does not have any spaces or invalid characters*)
and (getusername.getText().toString() *has more than 3 characters*) {

Toast.makeText(this, "Success.",Toast.LENGTH_SHORT).show();

} else if (getusername.getText().toString() *has spaces or invalid characters*) {

Toast.makeText(this, "Invalid Characters",Toast.LENGTH_SHORT).show();

} else if (getusername.getText().toString() *does not have more than 3 characters*) {

Toast.makeText(this, "Not enough characters开发者_Go百科",Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(this, "Unknown Error",Toast.LENGTH_SHORT).show();

}

This shows a general idea of what i'm trying to accomplish.

Thank you in advance.


You can use an InputFilter to block all unwanted characters. Just call setFilters and pass it an array (length 1 in this case) of filters that you would like to use. Then you don't have to worry about testing whether they are there. To test the length of the input, you can use the length() method of String.


Regex ftw.

   if (getusername.getText().toString().matches("[a-zA-Z0-9]{3}")){
      Toast.makeText(this, "Success").show();
   } else {
      Toast.makeText(this,
        "Please select exactly 3 alphanumeric characters only.").show();
   }

Regex may need to be changed to match your requirements

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜