繁体   English   中英

Email 验证使用正则表达式

[英]Email validation using regular expressions

我发现我可以使用正则表达式验证 email 输入。 但是,我不知道在哪里放置表达式。 我是否将它们放在我的 java controller 方法、实体类或 JSP 中?

如果您的 email 在字符串中,您可以编写类似以下内容来验证 email:

String email;
.
.  // load the email string
. 
if (email.matches("^[A-Za-z0-9_.]+[@][A-Za-z.]+$"))
{
.
.
.
}
else
    throw new EmailNotValidException();

我认为您可以创建一些EmailValidatorClass class ,只要您需要验证 email 地址,就可以在项目中使用它们:

import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import java.util.StringTokenizer;

/**
  * A class to provide stronger validation of email addresses.      
  *
  */
 public class EmailAddressValidator
 {
   public static boolean isValidEmailAddress(String emailAddress)
   {
     // a null string is invalid
     if ( emailAddress == null )
       return false;

     // a string without a "@" is an invalid email address
     if ( emailAddress.indexOf("@") < 0 )
       return false;

     // a string without a "."  is an invalid email address
     if ( emailAddress.indexOf(".") < 0 )
       return false;

     if ( lastEmailFieldTwoCharsOrMore(emailAddress) == false )
       return false;

     try
     {
       InternetAddress internetAddress = new InternetAddress(emailAddress);
       return true;
     }
     vcatch (AddressException ae)
     {
       // log exception
            return false;
     }
   }


   /**
    * Returns true if the last email field (i.e., the country code, or something
    * like .com, .biz, .cc, etc.) is two chars or more in length, which it really
    * must be to be legal.
    */
   private static boolean lastEmailFieldTwoCharsOrMore(String emailAddress)
   {
     if (emailAddress == null) return false;
     StringTokenizer st = new StringTokenizer(emailAddress,".");
     String lastToken = null;
     while ( st.hasMoreTokens() )
     {
       lastToken = st.nextToken();
     }

     if ( lastToken.length() >= 2 )
     {
       return true;
     }
     else
     {
       return false;
     }
   }
 }
String expression = "[A-Za-z]+@+[A-Za-z]+\\.+[A-Za-z]{2,4}+$";
Pattern p = Pattern.compile(expression);
Matcher m = p.matcher(txtValidate.getText());
if(!m.matches())
{
JOpyionPane.showMessageDialog(null, "Email not valid");
}

仅使用正则表达式无法创建正确的 email 验证。

这是关于如何(几乎)正确验证 email 地址的描述。


电子邮件根据RFC 5321RFC 5322进行验证。 以下是 email 语法的简化形式定义:

addr-spec = local-part "@" domain
local-part = dot-atom-text / quoted-string
dot-atom-text = atom *("." atom)
atom = 1*atext
atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
ALPHA = ASCII characters in the range ‘a’ (ACSII code 0x61) through ‘z’ (ACSII code 0x7A) and ‘A’ (ACSII code 0x41) through ‘Z’ (ACSII code 0x5A)
DIGIT = ASCII characters in the range ‘0’ (ACSII code 0x30) through ‘9’ (ACSII code 0x39)
specials = "(" / ")" / "<" / ">" / "[" / "]" / ":" / ";" / "@" / "\" / "," / "."
quoted-string = “ *(qcontent) “
qcontent = qtext / quoted-pair
qtext = 0x21 / 0x23-0x5B / 0x5D-0x7E; All ASCII printable characters instead of “ and \
quoted-pair = \ (VCHAR / WSP)
VCHAR = 0x21-0x7E; All ASCII printable characters
WSP = 0x20 / 0x09; ASCII Space or tab characters

除了这些规则之外, quoted-pair还可以放在local-part内的任何位置。 请注意,不使用特殊字符组。 这些字符既不能出现在 email 的本地部分中,也不能出现在域部分中。 只要整个 email 的总长度小于 256 个字符, local-part的长度最多为 64 个字符, domain 部分的长度最多为 255 个字符(如果它应该是有效的 DNS 域名)。

域名根据RFC 1034RFC 1123进行验证。 以下是域名语法的正式定义:

domain = subdomain / " " 
subdomain = label / subdomain "." label
label = let-dig *(*(ldh-str) let-dig)
ldh-str = let-dig-hyp / let-dig-hyp ldh-str
let-dig-hyp = let-dig / "-"
let-dig = ALPHA / DIGIT

此外, RFC 1034限制为 255 个 ASCII 符号,将label 限制为 63 个 ASCII 符号。

Apache 公共验证库(在问题的评论中提到)是一个好的开始。 它包含域验证和 email 验证,尽管我上次检查它在 email 验证中有一些错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM