class func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
}
I use this function to validate email in my login form. I can't understand how to rise this event from my textfield.
Using like this
if(username.isEqualToString("") || [!LoginController, testStr == self.username]) {
self.dismissViewControllerAnimated(true, completion: nil)
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Please enter valid username"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
return
}
But getting unresolved error at teststr
. I am new to Swift. Can any body explain me how to solve this?
Three Methods to Validate Email in SwiftCreating a custom class conforming to RawRepresentable which initializes only if a valid email address is provided. Utilizing Swift's own “specialized regular expression object” to match valid email addresses.
<input type="email" name="email" pattern="[a-z0-9. _%+-]+@[a-z0-9. -]+\. [a-z]{2,}$" title="please enter valid email [[email protected]]."> you can add title also to show a validity message.
You need to connect to the chosen SMTP server and check if an email address exists. If the server replies with (250 OK), the email address is valid. If the client gets a negative response ( 550-5.1. 1 User Unknown ), the address does not exist.
A valid email address consists of an email prefix and an email domain, both in acceptable formats. The prefix appears to the left of the @ symbol. The domain appears to the right of the @ symbol. For example, in the address [email protected], "example" is the email prefix, and "mail.com" is the email domain.
Swift 4.2 and Xcode 10
For me, other answers were returning true if there are more then two dots after the domain name. I found this answer where it handles that condition properly.
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{1,4}$"
let emailTest = NSPredicate(format:"SELF MATCHES[c] %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
Happy Coding 😀
Apple Swift version 5.1.3 with Xcode 11.4
extension String {
func isEmail()->Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}
}
Use it :
if let _textfieldText = textField.text {
if _textfieldText.isEmail() {
print("Okay Email go ahead")
}else{
print("Enter a valid email address first.")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With