[英]Email validation in Java without using regular expression
我知道使用Regex驗證電子郵件只需 3-4 行代碼。 但是,我希望在without using
Regex.
without using
驗證電子郵件Regex.
在某種程度上,代碼成功地通過了幾乎所有的驗證,但是,仍然無法弄清楚 - 如何避免特殊字符成為電子郵件地址的第一個和最后一個字符。
specialChars 列表 = {'!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '/', '~', '[', ']'} ;
我在看的是:
如果用戶名部分 (
abc.xyz
@gmail.com) 以任何特殊字符開頭或結尾,則應觸發“電子郵件地址無效”錯誤。 域部分也是如此。
例如...以下電子郵件 ID列表應打印“無效電子郵件 ID” error message
#abc.xyz@gmail.com
abc.xyz&@gmail.com
abc.xyz&@!gmail.com
abc.xyz&@gmail.com!
import java.util.Scanner;
public class Email_Validation {
public static void main(String[] args) {
// User-input code
Scanner scan = new Scanner(System.in);
System.out.println("Enter your email address");
String email = scan.next();
// Code to check if email ends with '.' (period sign)
boolean checkEndDot = false;
checkEndDot = email.endsWith(".");
// Code to find out last index of '@' sign
int indexOfAt = email.indexOf('@');
int lastIndexOfAt = email.lastIndexOf('.');
//Code to check occurence of @ in the email address
int countOfAt = 0;
for (int i = 0; i < email.length(); i++) {
if(email.charAt(i)=='@')
countOfAt++; }
// Code to check occurence of [period sign i..e, "."] after @
String buffering = email.substring(email.indexOf('@')+1, email.length());
int len = buffering.length();
int countOfDotAfterAt = 0;
for (int i=0; i < len; i++) {
if(buffering.charAt(i)=='.')
countOfDotAfterAt++; }
// Code to print userName & domainName
String userName = email.substring(0, email.indexOf('@'));
String domainName = email.substring(email.indexOf('@')+1, email.length());
System.out.println("\n");
if ((countOfAt==1) && (userName.endsWith(".")==false) && (countOfDotAfterAt ==1) &&
((indexOfAt+3) <= (lastIndexOfAt) && !checkEndDot)) {
System.out.println("\"Valid email address\"");}
else {
System.out.println("\n\"Invalid email address\""); }
System.out.println("\n");
System.out.println("User name: " +userName+ "\n" + "Domain name: " +domainName);
}
}
我如何解決這個問題?
這個怎么樣:
public class EmailMe {
private static Set<Character> bad = new HashSet<>();
public static void main(String[] args) {
char[] specialChars = new char[] {'!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '/', '~', '[', ']'} ;
for (char c : specialChars) {
bad.add(c);
}
check("#abc.xyz@gmail.com");
check("abc.xyz&@gmail.com");
check("abc.xyz&@!gmail.com");
check("abc.xyz&@gmail.com!");
}
public static void check(String email) {
String name = email.substring(0, email.indexOf('@'));
String domain = email.substring(email.indexOf('@')+1, email.length());
// String[] split = email.split("@");
checkAgain(name);
checkAgain(domain);
}
public static void checkAgain(String part) {
if (bad.contains(part.charAt(0))) System.out.println("bad start:"+part);
if (bad.contains(part.charAt(part.length()-1))) System.out.println("bad end:"+part);
}
}
所以,看看String API。 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
具體來說,你有 String.length() 和 String.charAt()。 因此,您可以非常非常輕松地從 String 中獲取第一個和最后一個字符。 你已經在你的代碼中做到了這一點; 假設你已經得到了。
你可以在這里運行一個很長的 if 語句;
char first = email.charAt(0);
if (first == '!' || first == '#' || <more here>) {
return false;
}
但這可能會讓人頭疼。 另一種方法是使用 Set,如果您需要多次檢查,則效率更高。 (查找 HashSet 通常非常快。)例如,您只需創建一次集合,然后就可以通過 Set.contains(first) 多次使用它。
我使用 Apache Commons 庫中的EmailValidator 。
上面的一個例子,
String email = "anEmailAddress@domain.com";
EmailValidator validator = EmailValidator.getInstance();
if (!validator.isValid(email)) {
// The email is not valid.
}
或者
if (!EmailValidator.getInstance().isValid("anEmailAddress@domain.com")) {
// The email is not valid.
}
如果您使用的是 maven,則可以使用此依賴項,
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.4.0</version>
<type>jar</type>
</dependency>
檢查下面的代碼,我相信它滿足您的電子郵件驗證。
Apache 常見的 lang maven 依賴項。
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
Java電子郵件驗證實用程序代碼。
public class EmailValidationUtility {
private static final String[] SPECIAL_CHARACTERS_FOR_USERNAME = new String[] {
"..", "__", ",", "/", "<", ">", "?", ";", ":", "\"", "\"",
"{", "}", "[", "]", "|", "\\", "!", "@", "#", "$", "%", "^",
"&", "*", "(", ")", "+", "=", "~", "`" };
private static final char[] SPECIAL_CHARACTERS_WITH_NUMBERS = new char[] {
'.', ',', '/', '<', '>', '?', ';', ':', '\'', '\"', '{',
'}', '[', ']', '|', '\\', '!', '@', '#', '$', '%', '^', '&',
'*', '(', ')', '-', '_', '+', '=', '~', '`', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '0' };
/**
* Method to validate the input email is valid or not.
*
* @param email the email
* @return true, if is email valid
*/
public static boolean isEmailValid(String email) {
String[] emailChunks = StringUtils
.splitByWholeSeparatorPreserveAllTokens(email,
"@");
if (emailChunks.length != 2 || isEmailUserNameInvalid(emailChunks[0])
|| StringUtils.isBlank(emailChunks[1])) {
return false;
}
String[] domainNames = StringUtils
.splitByWholeSeparatorPreserveAllTokens(emailChunks[1],
".");
if (domainNames.length < 2) {
return false;
}
int topLevelDomainNameIndex = domainNames.length - 1;
if (isTopLevelDomainNameInvalid(domainNames[topLevelDomainNameIndex])) {
return false;
}
domainNames = ArrayUtils.remove(domainNames, topLevelDomainNameIndex);
return (isDomainNameValid(domainNames));
}
private static boolean isEmailUserNameInvalid(String emailUserName) {
return (StringUtils.isBlank(emailUserName) || StringUtils.containsAny(
emailUserName, SPECIAL_CHARACTERS_FOR_USERNAME));
}
private static boolean isTopLevelDomainNameInvalid(String topLevelDomain) {
return (StringUtils.isBlank(topLevelDomain) || StringUtils.containsAny(
topLevelDomain, SPECIAL_CHARACTERS_WITH_NUMBERS));
}
private static boolean isDomainNameValid(String[] domainNames) {
for (String domainName : domainNames) {
if ((StringUtils.isBlank(domainName) || StringUtils.containsAny(
domainName, SPECIAL_CHARACTERS_WITH_NUMBERS))) {
return false;
}
}
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.