Created
September 24, 2017 12:33
-
-
Save moderateepheezy/360dbb8afe5a31aa8c10ee7563d38e3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func isValidEmailAddress(email: String) -> Bool { | |
var returnValue = true | |
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}" | |
do { | |
let regex = try NSRegularExpression(pattern: emailRegEx) | |
let nsString = email as NSString | |
let results = regex.matches(in: email, range: NSRange(location: 0, length: nsString.length)) | |
if results.count == 0 | |
{ | |
returnValue = false | |
} | |
} catch let error as NSError { | |
print("invalid regex: \(error.localizedDescription)") | |
returnValue = false | |
} | |
return returnValue | |
} | |
//Use with SkyFloatingLabelTextField | |
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
if self.emailTextField == textField{ | |
if let text = textField.text{ | |
let isEmailValid = isValidEmailAddress(emailAddressString: text) | |
emailTextField.errorMessage = (isEmailValid) ? "" : "Invalid Email" | |
} | |
} | |
return true | |
} | |
//Use with default UITextfield and a Label to display error | |
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
if self.emailTextField == textField{ | |
if let text = textField.text{ | |
let isEmailValid = isValidEmailAddress(emailAddressString: text) | |
errorLabel.text = (isEmailValid) ? "" : "Invalid Email" | |
errorLabel.isHidden = isEmailValid | |
} | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment