aks
aks

Reputation: 1859

regular expression for email validation in Java

I am using the follwoing regular expression

(".+@.+\\.[a-z]+")

Bit it accepts #@#.com as a valid email. What's the pattern I should use?

Upvotes: 8

Views: 24597

Answers (7)

Peter Stoilkov
Peter Stoilkov

Reputation: 11

This is my regex for email validation:

(([a-zA-Z0-9]+)([\.\-_]?)([a-zA-Z0-9]+)([\.\-_]?)([a-zA-Z0-9]+)?)(@)([a-zA-Z]+.[A-Za-z]+\.?([a-zA-Z0-9]+)\.?([a-zA-Z0-9]+))

For username it allows ".", "_", "-" for separators. After "@" allows only "." and "-". Can be easy modified for more words.

Upvotes: 0

Nitin Pawar
Nitin Pawar

Reputation: 936

import java.util.regex.*;

class ValidateEmailPhone{

    public static void main(String args[]){

        //phone no validation starts with 9 and of 10 digit
        System.out.println(Pattern.matches("[9]{1}[0-9]{9}", "9999999999"));

        //email validation
        System.out.println(Pattern.matches("[a-zA-Z0-9]{1,}[@]{1}[a-z]{5,}[.]{1}+[a-z]{3}", "[email protected]"));
    }
}

Upvotes: 0

Mahdi Esmaeili
Mahdi Esmaeili

Reputation: 575

[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}

Upvotes: 1

sp00m
sp00m

Reputation: 48837

I usually use the following one:

([a-zA-Z0-9]+(?:[._+-][a-zA-Z0-9]+)*)@([a-zA-Z0-9]+(?:[.-][a-zA-Z0-9]+)*[.][a-zA-Z]{2,})

Upvotes: 0

CoolBeans
CoolBeans

Reputation: 20820

You should use apache-commons email validator. You can get the jar file from here.

Here is a simple example of how to use it:

import org.apache.commons.validator.routines.EmailValidator;

boolean isValidEmail = EmailValidator.getInstance().isValid(emailAddress);

Upvotes: 29

Konstantin Spirin
Konstantin Spirin

Reputation: 21311

If somebody wants to enter non-existent email address he'll do it whatever format validation you choose.

The only way to check that user owns email he entered is to send confirmation (or activation) link to that address and ask user to click it.

So don't try to make life of your users harder. Checking for presence of @ is good enough.

Upvotes: 1

David Z
David Z

Reputation: 131800

Here's a web page that explains that better than I can: http://www.regular-expressions.info/email.html (EDIT: that appears to be a bit out of date since it refers to RFC 2822, which has been superseded by RFC 5322)

And another with an interesting take on the problem of validation: http://www.markussipila.info/pub/emailvalidator.php

Generally the best strategy for validating an email address is to just try sending mail to it.

Upvotes: 2

Related Questions