1

I have this textfield

TextField("Your e-mail...",
          text: $email)
  .keyboardType(.emailAddress)
  .textContentType(.emailAddress)
  .disableAutocorrection(true)
  .autocapitalization(.none)

I type anything and I see no error. Double @, multiple dots and so one. No error so far.

How is this supposed to work?

Duck
  • 34,902
  • 47
  • 248
  • 470
  • 2
    `textContentType(_:)` :- Sets the text content type for this view, which the system uses to offer suggestions while the user enters text on an iOS or tvOS device. its not use for validation – Nirav D Sep 29 '22 at 15:28
  • 1
    SwiftUI has no internal validation for email addresses. `.keyboardType` is providing the keyboard for email addresses and `.textContentType` enables the system to provide suggestions. Does [this](https://stackoverflow.com/questions/59988892/swiftui-email-validation) solve your question? – Carsten Sep 29 '22 at 15:29

1 Answers1

1

Your code only adds suggestions/custom keyboard for email addresses. It does not validate whether or not a user entered a valid email address.

To return whether or not the field contains a valid email address, you will need to run the entered string through a function that utilizes regex:

  func isValidEmailAddr(strToValidate: String) -> Bool {
       let emailValidationRegex = "^[\\p{L}0-9!#$%&'*+\\/=?^_`{|}~-][\\p{L}0-9.!#$%&'*+\\/=?^_`{|}~-]{0,63}@[\\p{L}0-9-]+(?:\\.[\\p{L}0-9-]{2,7})*$"
       let emailValidationPredicate = NSPredicate(format: "SELF MATCHES %@", emailValidationRegex)
       return emailValidationPredicate.evaluate(with: strToValidate)
}

If an error is returned, you can then do something with that response i.e. show an error to the user.

nickreps
  • 903
  • 8
  • 20