UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: What is a good practice to handle TextField validations?

Forums > SwiftUI

Hi 👋,

My current way shows the error text below the field if the func is triggered, after I hit enter on the TextField. This is not the best way as there are often multiple fields, and you don't hit enter on each one right? A thinkaround would be to show the error while typing until its correct and disable the form button til every field is validated. (Here I would need to create multiple funcs for e.g. passwords, or usernames)

TextField("Email", text: $email, onEditingChanged: { (isChanged) in
                 if !isChanged {
                      if self.textFieldValidatorEmail(self.email) {
                        self.isEmailValid = true
                      } else {
                        self.isEmailValid = false
                        self.email = ""
                      }
                }
})
.autocapitalization(.none)

if !self.isEmailValid {
      Text("Email is not valid") 
}

func textFieldValidatorEmail(_ string: String) -> Bool {
        if string.count > 100 {
            return false
        }
        let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" // short format
        let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
        return emailPredicate.evaluate(with: string)
}

Is this a good practice? What is a common way here? Or how are you approaching this?

2      

I tend to use a computed property aginst the isEmailValid to return true or false

then I have a isFormCompletedCorrectly variable which is computed to check the result of isEmailValid and any other fields you have

Finally I will apply a .disabled modifier against my submit button with a ternary check against isFormCompletedCorrectly

3      

not on laptop at the moment but can provide some code tomorrow evening if needed

hopefully above makes sense

2      

This video by Stewart Lynch Field Validation and MVVM for SwiftUI look like a good way to handle this

5      

Thank you both @rlong405 and @NigelGee. The video is very clear, and what I searched for. Will work my way through it and keep you posted.

2      

any time

i think i may have actually based my approach from that video - I certainly have watched it

2      

@rlong405 - Yes, it is similiar to your explained approach.

As an extension, to save line space I wrap if !text.isEmpty around the prompt Text, so that the validation prompt only is shown once the field is edited.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.