如何检查输入的电子邮件是否为电子邮件格式

时间:2016-04-04 10:59:59

标签: ios regex swift email

如何检查输入的电子邮件是否为coorct形式。像somename@gmail.com或任何。

这里是我的代码。我试过,但我的if语句中出现错误

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")
}

我需要的是,如果任何用户开始绑定电子邮件ID格式错误,我需要显示警告。

由于

3 个答案:

答案 0 :(得分:4)

希望有所帮助:

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

}

在您的代码中:

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")
}

答案 1 :(得分:1)

你可以试试这个

function documentTitleLength() {
    var len = 0;
    if (typeof(document)!="undefined") {
        if (typeof(document['title'])!="undefined") {
            len = document['title'].toString().length;
        }
    }
    return len;
}

Swift版

-(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];

}

使用电子邮件验证:

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!

}

更多来自此Email & Phone Validation in Swift

答案 2 :(得分:0)

这应该可以正常工作

   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
        }

用法:

if isValidEmail("xxxx@gmail.com"){
//email is valid
}