Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How is a textfield valid for just email addresses?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading