简体   繁体   English

else if语句,用于表示不需要的字符,并且对于edittext而言,字符的长度太短

[英]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. 我有一个名为getusernameedittext变量,希望在if语句中使用。

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. 我还想确保来自edittext的文本不少于3个字符。

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. 现在,我正在使用getusername.getText().toString()来获取edittext中的值,但是我想使用if语句,如果edittext中的字符与我的异常匹配,则该举杯“成功”。 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",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. 您可以使用InputFilter阻止所有不需要的字符。 Just call setFilters and pass it an array (length 1 in this case) of filters that you would like to use. 只需调用setFilters并将其使用的过滤器数组(在这种情况下为长度1)传递给它即可。 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. 要测试输入的长度,可以使用String的length()方法。

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 正则表达式可能需要更改以满足您的要求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM