开发者

Validating edittext in Android

I'm new to android & I'm trying to w开发者_Python百科rite 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! :)


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)


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜