The Miotz The Miotz - 3 months ago 100
Swift Question

Swift3: best way to validate the text entered by the user in a UITextField

Evening, in my app I have several

UITextfield
. Each one has to confirm to different limitations.

For example, I have a date Field, zipCode Field, SSN Field etc.

From the Apple Documentation I found:


Assign a delegate object to handle important tasks, such as:


  • Determining whether the user should be allowed to edit the text field’s contents.

  • Validating the text entered by the user.

  • Responding to taps in the keyboard’s return button.

  • Forwarding the user-entered text to other parts of your app.

  • Store a reference to the text field in one of your controller objects.




So I'm pretty sure I have to use delegates and
func textFieldDidEndEditing(_:)
.

The only way that came to my mind is to use a
switch
statement inside the
func textFieldDidEndEditing(_:)
to confirm the delegate to the difference limitation.

Is there a better, safer and faster pattern to face this problem?

Answer

You can set unique tag to your every text field and can compare in textFieldDidEndEditing or you can take IBOutlet of every textField and can compare it in textFieldDidEndEditing like,

 func textFieldDidEndEditing(textField: UITextField) {

    // By tag
    if textField.tag == 100  {

    }

    // OR

    //by outlet
    if textField == self.myTextField {


    }
}