Email Validation is wrong as per Regex

僤鯓⒐⒋嵵緔 提交于 2019-12-23 23:16:57

问题


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| )*\\r\\n)?(?:\\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| )*\\r\\n)?(?:\\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


回答1:


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 {
  let types = NSTextCheckingResult.CheckingType.link.rawValue
  guard
    let dataDetector = try? NSDataDetector(types: types),
    let match = dataDetector
      .matches(in: text, options: [], range: NSRangeFromString(text))
      .first,
    let absoluteString = match.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.




回答2:


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:




回答3:


you should have this code to don't allow subdomain.

    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
}


来源:https://stackoverflow.com/questions/41887760/email-validation-is-wrong-as-per-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!