Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a string be validated in Java?

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

like image 259
yash Avatar asked Sep 17 '10 05:09

yash


People also ask

How do you validate a string field?

The string length field validator checks if length of a String field is within a certain range, e.g. a password must contain at least 6 characters and no more than 12 characters. Using this validator in XML or annotation as follows: XML: using type=”stringlength” attribute in <validator> or <field-validator> elements.

What is string validation?

The StringValidator is used to test that a value conforms to a set of validation constraints. The validator is passed a JavaScript string. If a string is a masked string, it should be converted (using the MaskConverter) to a string (stripped of literals) before it is passed to the validator.

How do you validate data in Java?

In the Java programming language, the most natural way of doing data validation seems to be the following: try to build an object. if no problem is found, then just use the object. if one or more problems are found, then ensure the caller has enough information to tell the user about the issues.


2 Answers

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

like image 80
NullUserException Avatar answered Sep 29 '22 04:09

NullUserException


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;
}
like image 36
jsshah Avatar answered Sep 29 '22 04:09

jsshah