11

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

1

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

Comments

5

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;
}

2 Comments

There's really no point in checking for an empty string or trimming it because you can take care of those with regex.
the trim should be done AFTER the null check...or else you'll throw NullPointerException...
4

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.

Comments

2

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.