Jitendra Modi
Jitendra Modi

Reputation: 2394

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| )*\\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 "[email protected]" or any other wrong input but it will not work when I enter "[email protected]".

So,I find out that "[email protected]" 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 "[email protected]" 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

Upvotes: 2

Views: 826

Answers (3)

user887210
user887210

Reputation:

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("[email protected]")  // -> true
validate(" [email protected]") // -> false

This will make sure that the entire text is a single, valid email address without any superfluous characters.

Upvotes: 6

Md. Ibrahim Hassan
Md. Ibrahim Hassan

Reputation: 5477

Function Call:

let result = isValidEmail(testStr: "[email protected]")
        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:

enter image description here enter image description here

Upvotes: 1

Nikunj Damani
Nikunj Damani

Reputation: 753

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
}

Upvotes: 0

Related Questions