如何验证用户仅输入字符串或整数值或三个特殊字符(@和$)或它们的组合的EditText输入?
其他输入必须显示错误。
这是我的代码。
public static boolean Check_input_validation(String input){
if(!input.matches("^[a-zA-Z0-9]*$"))
return false;
else
return true;
}
答案 0 :(得分:1)
为EditText创建一个过滤器,并在过滤器中定义条件。例如,仅接受数字
final String[] acceptLtrs = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source.toString().isEmpty()) return null;
for (String acceptLtr : acceptLtrs) {
if (source.equals(acceptLtr)) {
return null; // will accept input
}
}
return ""; // will dismiss the input or you can show error here
}};
然后edittext.setFilters(new InputFilter[]{filter});
答案 1 :(得分:1)
使用regexp和TextChangedListener进行验证
EditText.addTextChangedListener(new TextWatcher() {
// ...
@Override
public void onTextChanged(CharSequence text, int start, int count, int after) {
validate(text.toString())
// your condition
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
}
});
public boolean validate(String str){
Pattern pattern;
Matcher matcher;
final String PATTERN = "[a-zA-Z0-9\-@#$]";
pattern = Pattern.compile(PATTERN);
matcher = pattern.matcher(str);
return matcher.matches();
}