Search code examples
swiftregexemail-validation

Can't do regex matching on object using an NSPredicate on a UITextField


Checking email regEx giving error:

Can't do regex matching on object error

in an extension to UITextField.

let emailRegEx : String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let e = emailTest.evaluate(with: self)

Solution

  • self is a UITextField. So you want self.text! so the predicate is run against the text of the text field.

    let e = emailTest.evaluate(with: self.text!)
    

    And yes, it's safe to force-unwrap the text property of a UITextField.