0

I am simply trying to validate an email using an expression. I have created a Struct that I use for my form fields.

 let emailRegEx = "[A-ZO-9a-z._%+-]+@[A-Za-zO-9.-J+|l.[A-Za-z]{2,64}"
    var isEmailValid: Bool {
        !email.isEmpty &&
        if email.ranges(of: emailRegEx, options: .regularExpression) == nil {
            return self
        }
    }

It keeps throwing this error...Cannot infer contextual base in reference to member 'regularExpression', and Expected expression after operator, lastly Extra argument 'options' in call.

jnpdx
  • 45,847
  • 6
  • 64
  • 94

1 Answers1

0

Your if is in the wrong place, and .ranges should be .range.

Assuming your emailRegEx is correct, try this:

var isEmailValid: Bool = !email.isEmpty && (email.range(of: emailRegEx, options: .regularExpression) != nil) 

Using a computed var, use this:

var isEmailValid: Bool {
    !email.isEmpty && (email.range(of: emailRegEx, options: .regularExpression) != nil)
}

You could also try this regex for email:

let emailRegEx = #"^\S+@\S+\.\S+$"#

Or

let emailRegEx = #"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"#

See also this SO post: How to validate an e-mail address in swift?