-3

Following is the code i am using:

Its always giving me output "Invalid email address"

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String name="";
do
{
    System.out.println("Email:");
    String email= br.readLine();
    if(!name.matches("^[a-zA-Z0-9]+@[a-zA-Z0-9]+(.[a-zA-Z]{2,})$"))
    System.out.println("Invalid email address");
    else
        break;  
}while(true);
nafas
  • 5,283
  • 3
  • 29
  • 57
Kapil Garg
  • 173
  • 1
  • 2
  • 8
  • 3
    You are getting email in email and matching name in if condition. – Shivam Oct 30 '15 at 10:29
  • Possible duplicate of [What is the best Java email address validation method?](http://stackoverflow.com/questions/624581/what-is-the-best-java-email-address-validation-method) – Autar Oct 30 '15 at 10:48

3 Answers3

5

Alternatively you can use apache validator

String email; //set the String...
System.out.println(EmailValidator.getInstance().isValid(email));
nafas
  • 5,283
  • 3
  • 29
  • 57
3
if(!name.matches("^[a-zA-Z0-9]+@[a-zA-Z0-9]+(.[a-zA-Z]{2,})$"))

should be

if(!email.matches("^[a-zA-Z0-9]+@[a-zA-Z0-9]+(.[a-zA-Z]{2,})$"))
sidgate
  • 14,650
  • 11
  • 68
  • 119
1

Probably you should call

email.matches("^[a-zA-Z0-9]+@[a-zA-Z0-9]+(.[a-zA-Z]{2,})$")

since name is constantly set to an empty string.

Číma
  • 11
  • 4