Reputation: 33589
I'm trying to use TextWatcher and regex for validating user input. Note that I have a complex regex:
edit.addTextChangedListener(new TextWatcher() {
private final Pattern m_regex = Pattern.compile("([a-zA-Z]{4}[ ]{0,1}){7}");
@Override
public void afterTextChanged(Editable s) {
String text = s.toString();
int length = text.length();
if(!m_regex.matcher(text).matches() && length > 0) {
s.delete(length - 1, length);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
The problem here is matcher can only check for 2 string states: match and no match with expression provided, but for input validation you also need to check for intermediate state - when a string doesn't match the pattern but doesn't contradict it either. Is there any way I could use my regex for validating string being typed in EditText
?
Upvotes: 1
Views: 386
Reputation: 5452
Do a match against another regex. Sorry if the answer seems silly, but as you said before, matcher can only check for 2 string states: match and no match.
EDIT:
I understood better your question. You can do this: test the input versus this regex
^(([a-zA-Z]{4}[ ]{0,1}){0,6}([a-zA-Z]{0,4})|([a-zA-Z]{4}))$
this will validate the text as being inserted. If it is ok let the user continue. Your regex should be used only when the user has finished to input text! -
OR, if you want to check if the user has finished to write do this: match the regex I wrote to see if the text is correct. If ok match yours and, if it matches, the user has finished inserting text.
Upvotes: 1