Matthew Kaplan
Matthew Kaplan

Reputation: 119

How to specify the type of text in UITextField

I'm trying to determine whether or not a user is entering a proper email address into a UITextField . I'm using this code but am getting the following error message.

 func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch) // I'm getting the error message here.
    let result = range != nil ? true : false
    return result
}
@IBAction func logIn(sender: AnyObject) {
    let validLogin = isValidEmail(testStr: field.text!)
    if validLogin {
        print("User entered valid input")
    } else {
        print("Invalid email address")
    }
}

This is the error message I'm getting: "Value of type 'String' has no member 'rangeOfString'"

I think this is because I don't have RegExKitLite installed but I'm not 100% sure. Even so, I tried installing the kit but I couldn't figure out how. I downloaded the file but I can't figure out how to add it in Xcode.

Upvotes: 0

Views: 50

Answers (1)

rmaddy
rmaddy

Reputation: 318774

If you are using Swift 3 or later, the lines:

let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result

needs to be:

let range = testStr.range(of: emailRegEx, options: [ .regularExpression ])
return range != nil

None of this needs a third party library.

You probably also want to make sure the whole string matches so you should add ^ to the start of the regular expression and add $ to the end.

Upvotes: 0

Related Questions