测试密码验证时为什么我没有收到错误消息?

时间:2018-12-05 15:50:20

标签: ios swift regex validation google-cloud-firestore

您可能会问这个问题,我是iOS /编程新手:我正在尝试实施密码验证,其中用户输入必须至少为 8个字符,包含1个大写字母,1个小写字母,1个数字和1个特殊字符。我决定在UIViewController上使用正则表达式和扩展名来执行此操作。 我读过某个地方,我必须在“ SignUpViewController”范围之外(不知道为什么)将其包括在内。 由于我仍在测试数据库,数据库确实具有开放的读/写规则,是不是它不检查此验证并每次都不注册用户的原因?请帮助

下面是代码:

import UIKit
import Firebase



class SignUpViewController: UIViewController {

    //Outlets
    @IBOutlet weak var firstNameText: UITextField!
    @IBOutlet weak var lastNameText: UITextField!
    @IBOutlet weak var emailText: UITextField!
    @IBOutlet weak var passwordText: UITextField!
    @IBOutlet weak var signUpButton: UIButton!


    override func viewDidLoad() {
        super.viewDidLoad()
    }


    @IBAction func signUpButtonTapped(_ sender: Any) {
        guard let firstName = firstNameText.text,
            let lastName = lastNameText.text,
            let email = emailText.text else { return }
            guard emailText.containsValidEmail() else {
            print("Invalid email. Please try again.")
            return
        }
            let password = passwordText.text else { return }
            guard passwordText.containsValidPassword() else {
            print("Invalid password. Please try again.")
            return
        }

        Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
            if let error = error {
                debugPrint("Error creating user: \(error.localizedDescription)")
            }
            let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
            changeRequest?.displayName = firstName
            changeRequest?.commitChanges(completion: { (error) in
                if let error = error {
                    debugPrint(error.localizedDescription)
                }
            })
            guard let userId = authResult?.user else { return }
            let userData: [String: Any] = [
                "firstName" : "",
                "lastName" : "",
                "User ID" : userId,
                "dateCreated" : FieldValue.serverTimestamp(),
                ]
            let db = Firestore.firestore()
            db.collection("users").document("one").setData(userData) { err in
                if let err = err {
                    print("Error writing document: \(err)")
                } else {
                    print("Document successfully written!")
                }
            }
        }
    }
}
public extension UITextField {
    func containsValidPassword() -> Bool {
        let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$@$!%*?&#])[A-Za-z\\dd$@$!%*?&#]{8,}"
        return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self.text)
    }
}
public extension UITextField {
    func containsValidEmail() -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self.text)
    }
}

更新12/14: 我通过添加密码和电子邮件验证扩展名来编辑原始帖子。我通过使用UITextField上的扩展名添加了密码验证。但是,当我尝试对电子邮件执行相同操作时,会出现编译错误。为什么会这样?

3 个答案:

答案 0 :(得分:0)

首先,您没有在代码中的任何地方调用isValidPassword函数。其次,如果您实际上要调用它,则会导致运行时异常,因为您试图将UIViewController实例传递给NSPredicate以匹配正则表达式。

您应该在isValidPassword上定义UITextField并验证其text属性。 (在这种情况下,我还将函数重命名为containsValidPassword,因为UITextField不是密码,它只包含密码的字符串。)

extension UITextField {
    func containsValidPassword() -> Bool {
        let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$@$!%*?&#])[A-Za-z\\dd$@$!%*?&#]{8,}"
        return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self.text)
    }
}

然后,您还需要致电验证:

@IBAction func signUpButtonTapped(_ sender: Any) {
    guard let firstName = firstNameText.text,
        let lastName = lastNameText.text,
        let email = emailText.text,
        let password = passwordText.text else { return }
    guard passwordText.containsValidPassword() else { 
        // Let the user know that their pwd is incorrect
        return
    }
...

答案 1 :(得分:0)

您正在使用BaseClass评估谓词,其中self的类型为self(这就是您要扩展的内容),您可能打算扩展UIViewController代替。

String

用法:

extension String {
    func isValidPassword() -> Bool {
        let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$@$!%*?&#])[A-Za-z\\dd$@$!%*?&#]{8,}"
        return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self)
    }
}

实际上我不确定扩展名是否适合这种情况,我建议您在let isValidPassword = "something".isValidPassword() -

中创建一个简单函数
SignUpViewController

或者,如果您想更具体一点,

func isValidPassword(password: String) -> Bool {
    let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$@$!%*?&#])[A-Za-z\\dd$@$!%*?&#]{8,}"
    return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: password)
}

答案 2 :(得分:0)

import UIKit
import Firebase



class SignUpViewController: UIViewController {

    //Outlets
    @IBOutlet weak var firstNameText: UITextField!
    @IBOutlet weak var lastNameText: UITextField!
    @IBOutlet weak var emailText: UITextField!
    @IBOutlet weak var passwordText: UITextField!
    @IBOutlet weak var signUpButton: UIButton!


    override func viewDidLoad() {
        super.viewDidLoad()
    }


    @IBAction func signUpButtonTapped(_ sender: Any) {
        guard let firstName = firstNameText.text,
            let lastName = lastNameText.text,
            let email = emailText.text else { return }
            guard emailText.containsValidEmail() else {
            print("Invalid email/password. Please try again.")
            return
        }
            guard let password = passwordText.text else { return }
            guard passwordText.containsValidPassword() else {
            print("Invalid email/password. Please try again.")
            return
        }

        Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
            if let error = error {
                debugPrint("Error creating user: \(error.localizedDescription)")
            }
            let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
            changeRequest?.displayName = firstName
            changeRequest?.commitChanges(completion: { (error) in
                if let error = error {
                    debugPrint(error.localizedDescription)
                }
            })
            guard let userId = authResult?.user else { return }
            let userData: [String: Any] = [
                "firstName" : "",
                "lastName" : "",
                "User ID" : userId,
                "dateCreated" : FieldValue.serverTimestamp(),
                ]
            let db = Firestore.firestore()
            db.collection("users").document("one").setData(userData) { err in
                if let err = err {
                    print("Error writing document: \(err)")
                } else {
                    print("Document successfully written!")
                }
            }
        }
    }
}
public extension UITextField {
    func containsValidPassword() -> Bool {
        let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$@$!%*?&#])[A-Za-z\\dd$@$!%*?&#]{8,}"
        return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self.text)
    }
}
public extension UITextField {
    func containsValidEmail() -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self.text)
    }
}

此格式按预期运行。谢谢