Email validation using RegEx and TextField text color

Hello,

I wrote a simple email validation test:

struct ContentView: View {

    @State private var email: String

    @State var emailIsValid: Bool = true

    

    public init(email: String = "")

    {

        self.email = email

    }

    

    var body: some View {

        Text("Hello, world!")

            .padding()

        

        TextField("Email", text: $email)

            .onChange(of: email) { newValue in

                if(newValue.range(of:"^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", options: .regularExpression) != nil) {

                    self.emailIsValid = true

                    print("valid")

                } else {

                    self.emailIsValid = false

                    print("invalid")

                }

            }

            .foregroundColor(emailIsValid ? Color.green : Color.red)

    }

}

And it works for the email like Test@gmail.com. Text is green. But if I type something like Testerka@gmail.com text stays red. But the print output says 'valid'.

Using a regular expression to validate an email address is doomed to failure.

To do this properly, use NSDataDetector, or NSPredicate.

There's a nice take on this here: https://www.swiftbysundell.com/articles/validating-email-addresses/

I found the problem. It is the spell checking. This is the fix: .disableAutocorrection(true)

I also tried to set properties of the text field for the email address. But it didn't work for me:

.keyboardType(.emailAddress)
.textContentType(.emailAddress)

You can find an interesting perspective on this at the following link: https://mail7.net/emailchecker.html

Email validation using RegEx and TextField text color
 
 
Q