views:

159

answers:

4

How can a string be validated in Java? I.e. only characters are allowed and not numbers? How about email validation?

+2  A: 

for string with only characters try

private boolean verifyLastName(String lname)
{
    lname = lname.trim();

    if(lname == null || lname.equals(""))
        return false;

    if(!lname.matches("[a-zA-Z]*"))
        return false;

    return true;
}

for email validation try

private boolean verifyEmail(String email)
{
    email = email.trim();

    if(email == null || email.equals(""))
        return false;

    if(!email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$"))
        return false;

    return true;
}
jsshah
There's really no point in checking for an empty string or trimming it because you can take care of those with regex.
NullUserException
I agree with NUE
jsshah
@jsshah, the `trim` should be done AFTER the null check...or else you'll throw NullPointerException...
st0le
+5  A: 

how a string can be validated in java?

A common way to do that is by using a regex, or Regular Expression. In Java you can use the String.matches(String regex) method. With regexes we say you match a string against a pattern If a match is successful, .matches() returns true.


only characters allowed and not numbers?

// You can use this pattern:
String regex = "^[a-zA-Z]+$";
if (str.matches(regex)) { 
    // ...
}

email validation?

Email addresses have a very complicated spec, which requires a monstrous regex to be accurate. This one is decent and short, but not exactly right:

String regex = "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b";
if (str.matches(regex)) { 
    // ...
}

If you really want to look into it: How to validate email and Comparing email validating regexes (PHP).


Here's an excellent resource to get started on regex:
http://www.regular-expressions.info

NullUserException
+3  A: 

For simple cases like that, go with RegExp as NullUserException already suggested. If you need more robust solution you can use some validation framework, i.e. Apache Commons Validator.

Paweł Dyda
A: 

If you have Apache commons-lang as a project dependency (and that is quite usual), you can use StringUtils.isAlpha(). If you have a more specific validation or do not want a dependency on commons-lang, you can do it with regular expressions and String.matches().

gpeche