Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 581
Andrea Miotto Avatar asked Aug 23 '16 12:08

Andrea Miotto


2 Answers

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 {


    }
}
like image 76
Ketan Parmar Avatar answered Sep 25 '22 16:09

Ketan Parmar


You are right, you will have to check the textfield, either you can check tags assigned for different text fields using switch statement like you said, or you can compare textfields itself,

if textfield1,textfield2 are outlets to two text fields, you can compare as following,

func textFieldDidEndEditing(textField: UITextField)
{
  if textField == textfield1
  {

  } 
  else if textField == textfield2
  {

  } 
}
like image 33
Annie Dev Avatar answered Sep 25 '22 16:09

Annie Dev