Use a category for alphabetics, combined with matches
, and delimiters for the beginning and end of input text, as such:
String valid = "abc";
String invalid = "abc3";
Pattern pattern = Pattern.compile("^\\p{Alpha}+$"); // use \\p{L} for Unicode support
Matcher matcher = pattern.matcher(valid);
System.out.println(matcher.matches());
matcher = pattern.matcher(invalid);
System.out.println(matcher.matches());
Output:
true
false
Note: this also happens to prevent empty inputs. If you want to allow them, use a different quantifier than +
, namely, *
.
Finally, since you will use that against a java.awt.TextField
, you can simply access its text with the method getText()
.