How can a string be validated in Java? I.e. only characters are allowed and not numbers? How about email validation?
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;
}
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
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.
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()
.