Reputation: 366
I have an EditText
(et) in my app. I want to be able to limit the character count AND to validate the input.
My input type is a string sequence for example, n = number, a = alpha. If I have say, 10 (max) chars, my input string will be something like...
aannnnnnna
I am having problems making this all work. It seems to be failing on my character count first (I commented the validation out). I am getting a strange problem where my text is doubling up. Here is my code...
et.setFilters(new InputFilter[] {
new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.equals("")) {
return source;
}
else {
String boxInput = source.toString();
String textFormat = options.getFormattedTextFormat();
int maxChars = options.getFormattedTextMaxChars();
if (maxChars > 0 && source.length() > maxChars) {
Toast.makeText(OpenForm.this, R.string.maxCharsText + " " + maxChars, Toast.LENGTH_SHORT).show();
boxInput = source.toString().substring(0,maxChars - 1);
source = boxInput;
}
if (!textFormat.isEmpty()) {
for (int i = 0; i < boxInput.length(); i++) {
char c = boxInput.charAt(i);
char test = textFormat.charAt(i);
if (test == 'n' && !Character.isDigit(c)) {
// Testing for a number, but character is not a number
Toast.makeText(OpenForm.this, R.string.badNumber + " " + i, Toast.LENGTH_SHORT).show();
} else if (test == 'a' && Character.isDigit(c)) {
// Testing for a letter but character is a number
Toast.makeText(OpenForm.this, R.string.badLetter + " " + i, Toast.LENGTH_SHORT).show();
}
//return boxInput;
}
}
return boxInput;
}
}
}
});
Upvotes: 0
Views: 75
Reputation: 3046
In XML you can add this.
android:maxLength="10"
to get the text from it to validate you can do this..
String text = editText.getText().toString().trim();
if (text.equals("whatev") {
}
To limit the edit text programmatically....
InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.LengthFilter(10);
editText.setFilters(filter);
You can still get the text out of it like above.
Upvotes: 2