How to validate an e-mail address in swift?
I would use NSPredicate
:
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
for versions of Swift earlier than 3.0:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
for versions of Swift earlier than 1.2:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(email)
}
return false
}
Validation of email in swift iOS application
You can validate email using a simple regex function which returns true
if it's valid otherwise false
You can validate it when user hits Done/Enter on keyboard event, such as editingDidEnd
. You can bind it from storyboard to class file like,
@IBAction func onPressDone(sender: UITextField){
if txtEmaildAddress.text.isEmpty {
println("enter email address") //prompt ALert or toast
}
else if self.validate(txtEmaildAddress.text) {
println("Invalid email address") // prompt alert for invalid email
}
}
func validate(YourEMailAddress: String) -> Bool {
let REGEX: String
REGEX = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", REGEX).evaluateWithObject(YourEMailAddress)
}
May help this method to validate easily.
HTH, Enjoy Coding !!
How to validate an e-mail address in swift?
I would use NSPredicate
:
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
for versions of Swift earlier than 3.0:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
for versions of Swift earlier than 1.2:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(email)
}
return false
}
What are best practices for validating email addresses in Swift?
Seems pretty straightforward. If you're having issues with your Swift conversion, if might be beneficial to see what you've actually tried.
This works for me:
func validateEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
}
validateEmail("test@google.com") // true
validateEmail("invalid@@google.com") // false
Email & Phone Validation in Swift
Yes your Error is below in XCode 6.1
This error is occurs because of if
conditional have to Bool
return type, but in Your if condition Return type is NSPredicate
so that you got error swift: Bound value in a conditional binding must be of Optional type you can solve as below.
var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
if phoneTest.evaluateWithObject(value) {
return (true, .NoError)
}
return (false, .PhoneNumber)
}
Email-Validations in Swift.
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
Use of Email-validation:
if isValidEmail("kirit@gmail.com"){
print("Validate EmailID")
}
else{
print("invalide EmailID")
}
Phone-Number Validation in Swift
func validate(value: String) -> Bool {
let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
how to check the entered email is in email format
Hope it helps:
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
In your code:
import UIKit
extension String {
func matchPattern(patStr:String)->Bool {
var isMatch:Bool = false
do {
let regex = try NSRegularExpression(pattern: patStr, options: [.CaseInsensitive])
let result = regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, characters.count))
if (result != nil)
{
isMatch = true
}
}
catch {
isMatch = false
}
return isMatch
}
}
class RegisterVC: UIViewController {
@IBOutlet weak var EmailField: UITextField!
@IBOutlet weak var LocationField: UITextField!
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var passWordField: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
@IBAction func SignUpBtnPress(sender: AnyObject) {
let Email:NSString = EmailField.text!
let Location:NSString = LocationField.text!
let username:NSString = userNameField.text!
let password:NSString = passWordField.text!
let confirm_password:NSString = confirmPasswordField.text!
if isValidEmail(Email) == true{
{
print("this is e-mail!")
}
else if ( Email.isEqualToString("") || Location.isEqualToString("") || username.isEqualToString("") || password.isEqualToString("") || confirm_password.isEqualToString("") ) {
let alertController = UIAlertController(title: "Alert", message: "All Field Are Mnditory.", preferredStyle: UIAlertControllerStyle.Alert)
let DestructiveAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Settings")
}
alertController.addAction(DestructiveAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else if ( !password.isEqual(confirm_password) ) {
let alertController = UIAlertController(title: "Alert", message: "Password Din't Match.", preferredStyle: UIAlertControllerStyle.Alert)
let DestructiveAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print("Password Din't Match")
}
alertController.addAction(DestructiveAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
print("login sucess")
}
How do I verify an email address to a certain user in ios swift?
After you've created a user with their email and password, if there are no errors you send them a verification email.
import FirebaseAuth
Auth.auth().currentUser?.sendEmailVerification
{
(error) in
if error != nil
{
print(error!.localizedDescription)
return
}
else
{
//CHECK INBOX FOR CONFIRMATION LINK
}
}
Related Topics
How to Compress of Reduce the Size of an Image Before Uploading to Parse as Pffile? (Swift)
React Native: How to Select the Next Textinput After Pressing the "Next" Keyboard Button
Xcode 4: Create Ipa File Instead of .Xcarchive
Swift - Stored Values Order Is Completely Changed in Dictionary
Detect iOS App Entering Background
How to Change Multiplier Property For Nslayoutconstraint
Why Is Wkwebview Not Opening Links With Target="_Blank"
Passing Parameters to Addtarget:Action:Forcontrolevents
Error Opening iOS Simulator with iOS 8 Beta Version: "Unable to Boot the iOS Simulator"
Ios: How to Share Text and Image on Social Networks
Execute Action When Back Bar Button of Uinavigationcontroller Is Pressed
How to Write Text on Image in Objective-C (Ios)
Hide Separator Line on One Uitableviewcell
Using Nsuserdefaults on Arrays
Watchkit Extension - No Matching Provisioning Profiles Found
Resize Uiimage With Aspect Ratio