Email Validation is wrong as per Regex
I am using email validation into my project which method is like below
//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
}
OR
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
}
This both Regex works fine when I enter "modijecky@gmail.com" or any other wrong input but it will not work when I enter "modijecky@gmail.com.com".
So,I find out that "name@.com.com" is a valid email address and there are more sub-domains like this. So now I want user not to enter sub-domains. Is there any REGEX that validate email address within just one domain like "name@gmail.com" not with multiple domains or sub-domains.
I also try different Regex from google and implement it into project but same problem occurs.
Please help me with it.
Thank you
Don't reinvent the wheel:
Not Reinventing the Wheel: Email Validation in Swift
Basically you can use NSDataDetector
to do the heavy lifting and have everything consistent and updated to the way it works in macOS and iOS natively. Not only that but you also avoid regex headaches.
// 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
This will make sure that the entire text is a single, valid email address without any superfluous characters.
你应该有这个代码不允许子域名。
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
}
Function Call:
let result = isValidEmail(testStr: "test@test.com.op")
if (result)
{
print ("passed")
}
else{
print ("failed")
}
Function Definition:
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
}
Result:
链接地址: http://www.djcxy.com/p/92596.html下一篇: 电子邮件验证是错误的正则表达式