Validating edittext in Android

2020-02-06 17:39发布

问题:

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! :)

回答1:

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)


回答2:

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.



回答3:

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)"