创建用户之前,请检查Firebase错误以及textFields是否为空

时间:2018-08-19 05:45:23

标签: swift firebase firebase-authentication

我正在尝试检查注册错误以及textFields是否为空。这是一种工作,但是如果nameTextFieldaddressTextField为空,则允许用户注册用户。警报会正确弹出。

@IBAction func registerButton(_ sender: UIButton) {
    Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { user, error in
        if error != nil {
            if let errCode = AuthErrorCode(rawValue: error!._code) {

                switch errCode {
                case .invalidEmail:
                    self.errorMsg(title: "Error", message: "E-mail address format wrong")
                case .emailAlreadyInUse:
                    self.errorMsg(title: "Error", message: "E-mail is already in use")
                case .weakPassword:
                    self.errorMsg(title: "Error", message: "Weak password. Need at least 6 characters")
                default:
                    print("Create User Error: \(error!)")
                }
            }
            return
        } else {
            //Display errormsg for missing entry

            if (self.nameTextField.text?.isEmpty)! {
                self.missingText(title: "Ooops", message: "Please enter your name")

                if (self.addressTextField.text?.isEmpty)! {
                    self.missingText(title: "Ooops", message: "Please enter your address")
                    }
                } else {

        //Register userinfo in Firebase
        let ref = Database.database().reference()
        let usersRefrence = ref.child("users")
        let uid = user?.user.uid
        let newUserRefrence = usersRefrence.child(uid!)
        newUserRefrence.setValue(["Name": self.nameTextField.text!, "Address": self.addressTextField.text!])

        }
            self.registrationConfirmation(title: "Great", message: "Please sign in with the registered user")
    }
  })
}

1 个答案:

答案 0 :(得分:1)

在进行身份验证之前验证文本字段。

      guard let email = emailTextField.text, email.isValidEmail(), let password = passwordTextField.text, password != "" else {
        // show error for nil values
        return
    }

    // go with Autth

     Auth.auth().createUser(withEmail: email, password: password, completion

扩展验证电子邮件地址

extension String {
func isValidEmail() -> Bool {
    // here, `try!` will always succeed because the pattern is valid
    let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[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])?)*$", options: .caseInsensitive)
    return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}