-5

How can I check if the user entered a valid string? For example if the user entered "cat" then it would valid, but if the user entered "cat'12ed" then it would be invalid because it should include only letters.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
pavikirthi
  • 1,569
  • 3
  • 17
  • 26

4 Answers4

1

In Java, you can check to see if the String is alpha, or alphanumeric using pattern matching, like so:

public boolean validate(String myString) {
    if ( myString == null) return false;
    return myString.matches("[A-Za-z0-9]+");
}

There is also commons StringUtils which has an alphanumeric method.

Peter Hale
  • 119
  • 4
1

If you want your String to be valid if it has only letters you have to use patterns for example:

if(Pattern.matches("[a-zA-Z]+", yourString)) {
//ok it's valid
} else {
//no, it'n not valid
}
Lorenzo Barbagli
  • 1,241
  • 2
  • 16
  • 34
1

Try regex - this should work for you

System.out.println("cat".matches("[a-zA-Z]+"));

System.out.println("cat'12ed".matches("[a-zA-Z]+"));
gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – gunr2171 Feb 24 '16 at 21:53
1

You can also use Apache Commons StringUtils: StringUtils.isAlpha().

This question is a possible duplicate of this question.

Community
  • 1
  • 1
ahjaworski
  • 11
  • 1
  • 1