Validating edittext in Android

2020-02-06 16:44发布

I'm new to android & I'm trying to write an application for a project.

I need to check whether the user has entered 7 numbers followed by one alphabet in edittext. Example: 0000000x

How should I do that? TIA! :)

3条回答
家丑人穷心不美
2楼-- · 2020-02-06 17:22

Probably the best approach would be to use a TextWatcher passed into the addTextChangedListener() method of the EditText. Here is an example use:

editText.addTextChangedListener(new TextWatcher() {
  @Override
  public void afterTextChanged(Editable e) {
    String textFromEditView = e.toString();
    validateText(textFromEditView);
  }

  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    //nothing needed here...
  }

  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
    //nothing needed here...
  }
});

I will leave the implementation of the validateText(String) method as an exercise for the reader, but I imagine it should be easy enough. I would either use:

  1. A simple Regular Expression.
  2. Or since this case is easy enough, checking that the length of the string is 8, and reviewing each character. There is a simple utility class to inspect the characteristics of characters. Character.isDigit(char) and Character.isLetter(char)
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-06 17:30

OnKeyListener listens to every key stroke in the view. you can use that to check whether the user has entered what he is supposed.

eg : if the no of char entered is 7 then

check if it follows the reqd expression format.

查看更多
倾城 Initia
4楼-- · 2020-02-06 17:41

There is a Class called Pattern in Android in that you can give Regular Expression to match your Requirements try this follwoing code i think it may work

Pattern p = Pattern.compile( "{7}" ); Matcher m = p.matcher(String.valueOf(edittext));

This will be true only if 7 characters are there in the Text box and then you can use some menthods like "Character.isDigit(char) and Character.isLetter(char)"

查看更多
登录 后发表回答