电子邮件验证是错误的正则表达式
我在我的项目中使用电子邮件验证,其方法如下所示
//MARK: isValidEmailID
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: (testStr)")
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:t| )*rn)?(?:t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|[|])|(?:\(?:t|[ -~]))))+(?: )*)|(?: )+)"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])).){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+.[-A-Za-z0-9._~!$&'()*+,;=:]+))])))(?:(?:(?:(?: )*(?:(?:(?:t| )*rn)?(?:t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
要么
func isValidEmailID(email: String) -> Bool {
let regExPattern: String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}"
let emailValidator: NSPredicate = NSPredicate(format: "SELF MATCHES %@", regExPattern)
let isValid: Bool = emailValidator.evaluateWithObject(email)
return isValid
}
这两个正则表达式工作正常,当我输入“modijecky@gmail.com”或任何其他错误的输入,但它不会工作,当我输入“modijecky@gmail.com.com”。
因此,我发现“name @ .com.com”是一个有效的电子邮件地址,并且有更多的子域名。 所以现在我想让用户不要进入子域。 是否有任何REGEX验证一个域中的电子邮件地址,如“name@gmail.com”而不是多个域或子域。
我也尝试从谷歌不同的正则表达式,并将其实施到项目中,但同样的问题发生。
请帮助我。
谢谢
不要重新发明轮子:
不重新发明轮子:Swift中的电子邮件验证
基本上,你可以使用NSDataDetector
来完成繁重的工作,并且一切都保持一致,并且可以在MacOS和iOS本地运行。 不仅如此,而且你也避免了正则表达式的问题。
// Simplifying the example from the website a bit
import Foundation
func validate(_ text: String) -> Bool {
guard let dataDetector = try?
NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
return false
}
let allMatches = dataDetector.matches(in: text,
options: [],
range: NSMakeRange(0, (text as NSString).length))
guard let absoluteString = allMatches.first?.url?.absoluteString else { return false }
return absoluteString == "mailto:(text)"
}
validate("test@gmail.com") // -> true
validate(" test@gmail.com") // -> false
这将确保整个文本是一个单一的,有效的电子邮件地址,没有任何多余的字符。
你应该有这个代码不允许子域名。
func isValidEmail(email:String) -> Bool {
if email.range(of: "@") == nil || email.range(of: ".") == nil{
return false
}
let accountName = email.substring(to: email.range(of: "@")!.lowerBound)
let domainName = email.substring(from: email.range(of: "@")!.upperBound)
let subDomain = domainName.substring(from: email.range(of: ".")!.lowerBound)
//filter for user name
let unWantedInUName = " ~!@#$^&*()={}[]|;’:"<>,?/`";
//filter for domain
let unWantedInDomain = " ~!@#$%^&*()={}[]|;’:"<>,+?/`";
//filter for subdomain
let unWantedInSub = " `~!@#$%^&*()={}[]:";’<>,?/1234567890";
//subdomain should not be less that 2 and not greater 6
if(!(subDomain.characters.count>=2 && subDomain.characters.count<=6)) {
return false;
}
if (accountName == "" || accountName.rangeOfCharacter(from: CharacterSet.init(charactersIn: unWantedInUName)) != nil || domainName == "" || domainName.rangeOfCharacter(from: CharacterSet.init(charactersIn: unWantedInDomain)) != nil || subDomain == "" || subDomain.rangeOfCharacter(from: CharacterSet.init(charactersIn: unWantedInSub)) != nil ) {
return false
}
return true
}
函数调用:
let result = isValidEmail(testStr: "test@test.com.op")
if (result)
{
print ("passed")
}
else{
print ("failed")
}
功能定义:
func isValidEmail(testStr:String) -> Bool {
// print("validate calendar: (testStr)")
var returnValue : Bool = false
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
if (emailTest.evaluate(with: testStr))
{
let fullNameArr = testStr.components(separatedBy: "@")
let IdName = fullNameArr[0]
let domainName = fullNameArr[1]
var number = 0
let string = domainName
for character in domainName.characters {
if character == "."
{
number = number + 1
}
}
if number <= 1
{
returnValue = true
}
}
return returnValue
}
结果:
链接地址: http://www.djcxy.com/p/92595.html