Android在用户输入时验证输入

时间:2015-04-21 10:30:48

标签: android android-edittext

我有EditText用户必须输入电话号码。电话号码的模式为:^5[4][0-9]{10}$第一个数字是5,第二个是4,后跟10位数。

我已尝试使用以下InputFilter

            InputFilter filter= new InputFilter() {
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    for (int i = start; i < end; i++) {
                        String checkMe = String.valueOf(source.charAt(i));

                        Pattern pattern = Pattern.compile("^5[4][0-9]{10}$");
                        Matcher matcher = pattern.matcher(checkMe);
                        boolean valid = matcher.matches();
                        if(!valid){
                            return "";
                        }
                    }
                    return null;
                }
            };

但这仅匹配完整的数字,我想在用户输入数字时进行验证。

想象一下这种情况:

User enters 6 -> Does not match the initial digit of the pattern so EditText stays empty
User enters 5 -> Matches the first digit of the pattern so EditText text = 5
User enters 3 -> Does not match the second digit of the pattern so EditText text = 5
User enters 4 -> Matches the second digit of the pattern so EditText text = 54
From now, if the user adds a digit, EditText will append that until the length of 10

我知道如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

使用TextWatcher界面

XML限制输入类型(数字)和最大字符数(12)

 <EditText
        ....
        android:inputType="number"
        android:maxLength="12" >

Java

editText.addTextChangedListener(new PhoneNumberTextWatcher());

TextWatcher界面

class PhoneNumberTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (s != null && s.length() > 0) {
                String number = s.toString();
                if (number.startsWith("5")) {
                    if (number.length() > 1)
                        if (!number.startsWith("54")) {
                            editText.setText("5");//if second number is not 4
                            editText.setSelection(editText.length()); // move the cursor to 1 position
                        }

                } else
                    editText.setText("");
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }