I need to restrict the input that can be entered into a TextInputEditText to two capital letters and one or two digits, as in AB01, CS8, XY99 or ND5.
So I wrote this method:
/**
* @return an InputFilter that restricts input to the format of two capital letters and one or two digits
*/
public static InputFilter getClientIdInputFilter() {
return (source, start, end, dest, dstart, dend) -> {
Log.v(DEBUG_TAG, "----\nsource: " + source + ", start: " + start + ", end: " + end + ", dest: " + dest + ", dstart: " + dstart + ", dend: " + dend);
String destTxt = dest.toString();
String input = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
Log.v(DEBUG_TAG, input);
if (input.matches("^[A-Z]{0,2}[0-9]{0,2}$")) {
if (input.length() == 1 && input.matches("^[0-9]$")) {
Log.v(DEBUG_TAG, "Invalid input A");
return "";
}
if (input.length() == 2 && !input.matches("^[A-Z]{2}$")) {
Log.v(DEBUG_TAG, "Invalid input B");
return "";
}
Log.v(DEBUG_TAG, "Valid input");
return null;
}
Log.v(DEBUG_TAG, "Invalid input C");
return "";
};
}
That I use like this:
TextInputEditText clientId = dialogView.findViewById(R.id.edit_text_client_id);
InputFilter[] clientIdFilters = new InputFilter[1];
clientIdFilters[0] = InputFilterUtils.getClientIdInputFilter();
clientId.setFilters(clientIdFilters);
It almost works perfectly...
The problem is that only when starting typing from an empty textfield, after the first two capital letters (so at the 3rd one) the field gets deleted completely. If, instead, a number is entered first (and gets correctly ignored), if you continue to type letters, when reaching the 3rd letter, this time the first two remains and the user can continue entering the digits...
I don't have a clue for this behavior (I added some logging entries, but it's not clear anyway)
Why are you using regex for this? This is a simple validation logic.