如何在iOS应用程序中验证电子邮件地址?

时间:2016-06-13 22:03:28

标签: ios swift textfield email-validation

我的主要目标是检查文本字段的输入是否正确(即电子邮件地址)。我在网上发现了很多emailIsValid种功能,但我认为我在考虑这个错误,是的,我确实想检查电子邮件是否正确,但我也想查看电子邮件是否正确。该函数工作正常但有一种方法我可以设置参数说(如果( self.isEmailValid(userEmail!= true))`)所以它也同时检查电子邮件是否不符合约束并抛出警报,就像我内置的那样。

我的代码工作正常,但它无法正常工作,我基本上是在电子邮件无效时尝试抛出错误。我应该在else if语句中改变什么才能实现这一点,或者我是否认为这一切都错了?

初学者。

@IBAction  func sendEmail(sender: AnyObject){

    let userEmail = emailTextField.text

    if (userEmail!.isEmpty){

        let myAlert = UIAlertController (title: "Alert",
        message: "Email field is required to continue.",
        preferredStyle: UIAlertControllerStyle.Alert)

        let okAction = UIAlertAction(title: "Ok",
        style: UIAlertActionStyle.Default, handler: nil)

        myAlert.addAction(okAction)

        self.presentViewController(myAlert, animated: true, completion: nil)

        return
    }

    else if self.isValidEmail(userEmail!){

        let myAlert = UIAlertController (title: "Alert",
        message: "Email field is required to continue.",
        preferredStyle: UIAlertControllerStyle.Alert)

        let okAction = UIAlertAction(title: "Ok",
        style: UIAlertActionStyle.Default, handler: nil)

        myAlert.addAction(okAction)

        self.presentViewController(myAlert, animated: true, completion: nil)

        return
    }

}

func isValidEmail(enteredEmail:String) -> Bool {

    let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
    return emailPredicate.evaluateWithObject(enteredEmail)

}

1 个答案:

答案 0 :(得分:0)

只需这样做。避免对!进行强行包装。最好使用Guard let语句并进行适当的错误处理。

@IBAction func sendEmail(sender: UITextField) {

    guard let userEmail = sender.text else {
        errorAlert()
        return 
    }

    if isValidEmail(userEmail) {
        //do your login stuff
    } else {
        errorAlert()
    }
}

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

func errorAlert() {
    //put your alert controller here
}