java - 使用 android 中允许的字符验证 EditText 输入

标签 java android

如何验证 EditText 上的输入,即用户仅输入字符串或整数值或三个特殊字符(@ 和 $)或这些字符的组合?

其他输入必须显示错误。

这是我的代码。

public static boolean Check_input_validation(String input){
if(!input.matches("^[a-zA-Z0-9]*$"))
    return false;
else
    return true;
}

最佳答案

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

关于java - 使用 android 中允许的字符验证 EditText 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54302552/

相关文章:

java - 三月两个日期之间的天数差异错误

java - 如何在hibernate条件中使用mysql的 "use index()"子句?

javascript - 如何停止youtube链接以在gmail模板中加载其他视频?在这种情况下,javascript或jquery有用吗?

java - 从 Selenium 测试 onbeforeunload 事件

android - 在模拟器中启动 AVD 时显示此 "Unable to locate adb"

java - 在 Camel DSL "to"中使用 Exchange 属性

java - 扩展 ListActivity 时 ActionBar 不工作

android - EditText 的首字母大写

java - Facebook SDK v3.5.2 - 从封闭 session 请求权限

android - 将 Appcloud 与 Jquery Mobile 结合使用