1

I have a textField into which the user types an email address. I want to activate the submit button at the instant the input text becomes a valid email address.

The validation works, but the code in shouldChangeCharactersInRange appears to execute one step behind the user input. So when the email is valid, the user still has to tap one more key before the button changes. And likewise, if the email address becomes invalid, the button doesn't change until one more key is tapped.

Note that this happens on the device too, not just in the simulator.

Code is below:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) {
    if emailIsValidFormat(textField.text) {
        emailSubmitButton.alpha = 1
    } else {
        emailSubmitButton.alpha = 0.4
    }
}
Naftali Beder
  • 1,066
  • 1
  • 10
  • 27

3 Answers3

2

The text hasn't changed yet when this method is called. You have to userange and replacementString to construct the email address, and then verify that.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • This worked! I looked at [this question](http://stackoverflow.com/questions/25621496/how-shouldchangecharactersinrange-works-in-swift) for some guidance on how to use `replacementString`. – Naftali Beder Feb 21 '15 at 18:53
2

Instead of implementing textField:shouldChangeCharactersInRange:replacementString:, it would probably be simpler to connect the “Editing Changed” event of your text field to an action in your view controller. The text field sends textField:shouldChangeCharactersInRange:replacementString: before it updates its text property, but it sends the “Editing Changed” event after it updates its text property.

Example:

connect Editing Changed event

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

move your code to another place, let call it: func validateEmail(emailTextField: UITextField) -> Bool here the important part:

yourTextField.addTarget(self, action: "validateEmail:", forControlEvents: .EditingChanged) or .ValueChanged

validateEmail: will be called everytime your string changed.

Pham Hoan
  • 2,107
  • 2
  • 20
  • 34