gpt4 book ai didi

java - 在 Java 中验证电子邮件

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:35:16 24 4
gpt4 key购买 nike

我有一张注册表,上面有姓名、电子邮件和密码。确认链接会发送到用户注册时的电子邮件地址。但在发送链接之前,我需要验证电子邮件地址。我用过:

public static boolean verifyEmailAddress(String regEmail) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(regEmail);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}

它显示有效的任何电子邮件,例如 yutr6767868@huymail.comk999////@sdmail.com

我从 request.getParameter 获取的电子邮件并将其存储在 regEmail 中。

我到底需要做什么才能让它发挥作用?

最佳答案

好的,这里有 3 个例子 http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

我想你需要的是

package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator{

private Pattern pattern;
private Matcher matcher;

private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@
[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

public EmailValidator(){
pattern = Pattern.compile(EMAIL_PATTERN);
}

/**
* Validate hex with regular expression
* @param hex hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex){

matcher = pattern.matcher(hex);
return matcher.matches();

}

整个组合意味着,电子邮件地址必须以“_A-Za-z0-9-”开头,可选后跟“.[_A-Za-z0-9-]”,并以“@”符号结尾。电子邮件的域名必须以“A-Za-z0-9”开头,后跟一级 Tld(.com、.net)“.[A-Za-z0-9]”,可选后跟二级 Tld ( .com.au, .com.my) “\.[A-Za-z]{2,}”,其中二级 Tld 必须以点“.”开头并且长度必须等于或大于 2 个字符。

例子

package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator{

private Pattern pattern;
private Matcher matcher;

private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@
[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

public EmailValidator(){
pattern = Pattern.compile(EMAIL_PATTERN);
}

/**
* Validate hex with regular expression
* @param hex hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex){

matcher = pattern.matcher(hex);
return matcher.matches();

}

关于java - 在 Java 中验证电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10042329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com