user1015523
user1015523

Reputation: 332

Validating String input has no numbers

I have found how to validate that an input is a number using try/catch but how do I go about validating that a user input is alphabetical only and contains no numbers?

Upvotes: 1

Views: 15717

Answers (3)

Jeffrey
Jeffrey

Reputation: 44808

public static boolean containsNumbers(String str){
    for(char ch : str.toCharArray()){
        if(Character.isDigit(ch)){
            return true;
        }
    }
    return false;
}

Upvotes: 2

NPE
NPE

Reputation: 500663

You could use a simple regular expression:

if (str.matches("[a-zA-Z]+$")) {
   // str consists entirely of letters
}

Note that this only works with letters A-Z and a-z. If you need to properly support Unicode, a better method is to loop over the characters of the string and use Character.isLetter().

Upvotes: 3

Salvatore Previti
Salvatore Previti

Reputation: 9070

One way is to use regular expressions.

private static Pattern p = Pattern.compile("^[A-Za-z]+$");

public static boolean match(String s) {
    return p.matcher(s).matches();
}

One other way can be iterate through all characters in your string and check if they are alphabetical or not.

Upvotes: 1

Related Questions