Skip to content

Instantly share code, notes, and snippets.

@dodikk
Created March 6, 2018 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dodikk/5dcc842344a1e9d7bb484d2bcc7333d0 to your computer and use it in GitHub Desktop.
Save dodikk/5dcc842344a1e9d7bb484d2bcc7333d0 to your computer and use it in GitHub Desktop.
Email validation regex from bootstrap
private static func validateEmailByBootstrapRegex(_ userInput: String) -> Bool
{
var emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegex)
return emailTest.evaluate(with: userInput)
}
// TODO: is NSPredicate any better
// than `(NSPredicate.numberOfMatches == 1)` ?
//
//
@dodikk
Copy link
Author

dodikk commented Mar 6, 2018

NSPredicate is less code

    public static func executeRegex_NSPredicate(
        _ regex: String,
        onUserInput userInput: String)
    -> Bool
    {
        let emailTest = NSPredicate(format:"SELF MATCHES %@", regex)
        return emailTest.evaluate(with: userInput)
    }
    public static func executeRegex_NumberOfMatches(
        _ regexText: String,
        onUserInput userInput: String)
    -> Bool
    {
        let regexOptions: NSRegularExpression.Options =
            .caseInsensitive
        
        let maybeRegex = try?
            NSRegularExpression(
                pattern: regexText   ,
                options: regexOptions)
        
        guard let regex = maybeRegex
        else
        {
            // no validation if parsing has failed
            // otherwise we would block a user
            //
            //
            return true
        }
        
        let defaultMatcherOptions =
            NSRegularExpression.MatchingOptions(rawValue: 0)
        
        precondition(!userInput.isEmpty)
        let entireStringRange = NSMakeRange(0, userInput.count)
        
        let posixLocale = Locale(identifier: "en_US_POSIX")
        let uppercaseUserInput = userInput.uppercased(with: posixLocale)
        
        let numberOfMatches =
            regex.numberOfMatches(
                in     : uppercaseUserInput   ,
                options: defaultMatcherOptions,
                range  : entireStringRange    )
        
        let result = (1 == numberOfMatches)
        return result
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment