I would recommend using a DocumentFilter
, which would allow you to perform a real time filter as the user types.
The following is a very basic example of filtering out unwanted characters and limit the length of how many characters can be entered
public class PhoneNumberDocumentFilter extends DocumentFilter {
protected static String[] VALID_VALUES = new String[]{"+", "-", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
private int maxLength = 21;
public PhoneNumberDocumentFilter(int maxLength) {
this.maxLength = maxLength;
}
public PhoneNumberDocumentFilter() {
}
protected String filter(String text) {
StringBuilder sb = new StringBuilder();
List<String> validValues = Arrays.asList(VALID_VALUES);
for (int index = 0; index < text.length(); index++) {
String value = text.substring(index, index + 1);
if (validValues.contains(value)) {
sb.append(value);
}
}
return sb.toString();
}
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
String value = filter(string);
if (value.length() > 0) {
if (maxLength > 0 && doc.getLength() + value.length() <= maxLength) {
super.insertString(fb, offset, value, attr);
}
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder(2);
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
String value = filter(text);
if (value.length() > 0) {
if (sb.length() > maxLength) {
length = sb.length() - maxLength;
if (length > 0) {
value = value.substring(0, length);
}
}
super.replace(fb, offset, length, value, attrs);
}
}
}
What it doesn't do is valid the format, I'll leave that up to you to figure out how you might do that