1

How to check whether the entered email is in coorect form. Like somename@gmail.com or any.

here my code.I tried but i am getting error in my if statement

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.
    }
@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 (Email.matchPattern("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$")==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")
}

what i need is, if any user start tying the email id is in wrong format, i need to show alert.

Thanks

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
user5513630
  • 1,709
  • 8
  • 24
  • 48
  • *" i am getting error in my if statement"* is a useless problem description. Which if statement and what error? – Martin R Apr 04 '16 at 11:06
  • http://stackoverflow.com/questions/27998409/email-phone-validation-in-swift/27998447#27998447 – Kirit Modi Apr 04 '16 at 11:23
  • There really is no good way to validate an email address other than actually contacting the host and seeing if it will accept the email. See this article: [I Knew How To Validate An Email Address Until I Read The RFC](http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/) –  Apr 04 '16 at 11:27

3 Answers3

4

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")
}
iVarun
  • 6,496
  • 2
  • 26
  • 34
  • i just copy your func method , but it not shwoing when i enter an unformat email?? – user5513630 Apr 04 '16 at 11:16
  • its ok , but how can i call this method inside my signupbutton pressd method – user5513630 Apr 04 '16 at 11:30
  • 1
    You need to expand the regex a little `emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,15}"` - A lot of domain endings now end in more than 4 characters. – Henry Apr 04 '16 at 20:32
1

You can try this

-(BOOL)isValidEmailAddress:(NSString *)email
{
    BOOL stricterFilter = YES; 
    NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString:laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];

}

Swift version

func isValidEmail(testStr:String) -> Bool {

println("validate emilId: \(testStr)")

let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"

var emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)

var result = emailTest?.evaluateWithObject(testStr)

return result!

}

Use of Email-validation:

   if isValidEmail(textField.text)
  {
      println("Validate EmailID")
  }
  else
  {
      println("invalide EmailID")
  }

more from this Email & Phone Validation in Swift

Community
  • 1
  • 1
viratpuar
  • 524
  • 1
  • 5
  • 22
0

this should be working fine

   func isValidEmail(testStr:String) -> Bool {
            let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
            let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
            let result = emailTest.evaluateWithObject(testStr)
            return result
        }

usage:

if isValidEmail("xxxx@gmail.com"){
//email is valid
}
Med Abida
  • 1,214
  • 11
  • 31
  • False. The following emails are valid and this test says that it is invalid `j@proseware.com9`, `js#internal@proseware.com` , `j_9@[129.126.118.1]`, ` js@proseware.com9` and the inverse for the following: `j.@server1.proseware.com`, `j..s@proseware.com` , `js@proseware..com` , `js@proseware..com` – archLucifer Sep 05 '17 at 06:40