-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,130
  • 1
  • 26
  • 52
Kapil Garg
  • 161
  • 1
  • 2
  • 7
  • 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,130
  • 1
  • 26
  • 52
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
  • 13,104
  • 9
  • 60
  • 107
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