0

I am trying to put some constraints on my EditText field in my app. For the fullname and some other fields, I would like to only allow letters, space and some other characters like '.' or '-'.

I saw some stuff online and put this together:

mFullnameView = (EditText) findViewById(R.id.activity_register_et_fullname);
TextWatcher fullnameTextWatcher = new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        validate(s.toString());
    }

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

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //
    }

    private void validate(String s) {
        if (!(Pattern.matches("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", s))) {
            if (s.length() > 0) {
                final String cleanText = s.substring(0, s.length());
                mFullnameView.setText(cleanText);
            }
        }
    }
};

However now my app freezes for a few seconds and then crashed when I try typing a "." in the EditText field, I do not know why this happens or how to resolve it.

halfer
  • 19,824
  • 17
  • 99
  • 186
user3718908x100
  • 7,939
  • 15
  • 64
  • 123
  • It might be easier to just restrict what the user can enter into the EditText to begin with, so that you don't have to try to validate. Like here: http://stackoverflow.com/a/23212485/2128028 – Everett Mar 21 '17 at 01:18

1 Answers1

1

If you change the text in TextWatcher , the method in TextWatcher will callback again. So , you should avoid recursive calls or use InputFilter.

    InputFilter[] filters = new InputFilter[1];
    filters[0] = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source == null) return null;
            Pattern p = Pattern.compile("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$");
            Matcher m = p.matcher(source.toString());
            StringBuilder builder = new StringBuilder();
            while (m.find()) {
                builder.append(m.group());
            }
            return builder.toString();
        }
    };
    mFullnameView.setFilters(filters);
Kilnn
  • 107
  • 8