Search code examples
javaregexswingvalidationjtextfield

Check if JTextField contains only letters or numbers


I have a JTextField where the user can type anything. What is a convenient way to check if the String of TextField.getText() does contain letters or numbers only? Basically I just want to avoid any other symbol (e.g. _^$. etc)

Thank you in advance


Solution

  • You could consider using the String method matches which takes a regular expression as an argument and determines whether the string matches the regular expression. For example, alphanumeric can be represented by the regular expression [a-zA-Z0-9]+ which matches the patter any lower case letter or uppercase letter or number at least 1 time.

    Consider the following code:

    String text = "axc";
    boolean match = text.matches("[a-zA-Z0-9]+");
    

    You might want to go through this Java Tutorial on regular expressions