There are so many questions and answers regarding this topic,but my problem is I have edit text in my app,there I need to enter a name,so I need to validate my edit text,to avoid spaces and special characters as the only name,and edit text can't be empty also.How can I do that without textwatcher.
Asked
Active
Viewed 9,383 times
1
-
Be specific, u need to validate on each keystroke or after a button click? – Brendon Oct 22 '15 at 06:33
-
When I click the add button to add Name,I need to show the error message whenever the field is empty or the field is only with special characters – acer Oct 22 '15 at 06:42
-
if(edittext1.matches("")){ e2.setError("Invalid Address"); } add on xml file->android:inputType="textFilter" – Android Oct 22 '15 at 06:45
-
1. What are special characters? 2. what you try? 3. You can show keyboard without group of characters/numbers 4. regular expression, like this: ^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$ from http://stackoverflow.com/questions/12018245/regular-expression-to-validate-username – AsfK Oct 22 '15 at 06:48
4 Answers
4
You can use a simple regular expression
public boolean isValidWord(String word) {
return word.matches("[A-Za-z][^.]*");
}
if return value is true then your input dont have a special char or spaces.. if false it may have special char or spaces.. simple and elegant..
Just call the method with the string paramater before add your name..

Dinithe Pieris
- 1,822
- 3
- 32
- 44

Brendon
- 1,368
- 1
- 12
- 28
-
For all other characters,this answer is good,but for the `.` (fullstop symbol) your code is not working – acer Oct 23 '15 at 17:35
0
You can use input filter to filter out special characters and white space
edittext.setFilters(new InputFilter[] { new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String regex = "a-z~@#$%^&*:;<>.,/}{+";
if(!dest.toString().contains(" ")||!dest.toString().matches("[" + regex + "]+")){
return null;
}
}
} });
I hope it helps you..

Fabin Paul
- 1,701
- 1
- 16
- 18
-1
edittext.setFilters(new InputFilter[] { new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String regex = "a-z~@#$%^&*:;<>.,/}{+";
if(!dest.toString().contains(" ")||!dest.toString().matches("[" + regex + "]+")){
return null;
}
}
} });

Nirav Shah
- 67
- 10