如何从Outlet Collection获取文本字段值以进行密码验证?

时间:2017-12-27 05:59:24

标签: swift xcode validation

我对Swift很新。我正在创建一个注册页面并对其应用验证。我想验证电子邮件和密码。我正在使用插座收藏,我也想知道如何从插座收藏中获取价值。这是代码。

if senderTag == 0           // Name
    {

    }

    else if senderTag == 1      // Email
    {

        func validateEmail(candidate: String) -> Bool {

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

            return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)


        }

        if validateEmail(candidate:How to use this?)



    }

    else if senderTag == 2
    {

        func isPasswordValid(_ password : String) -> Bool{

            let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$")

            return passwordTest.evaluate(with: password)
        }

    }

    else if senderTag == 3
    {

        func isPasswordValid(_ password : String) -> Bool{

            let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$")

            return passwordTest.evaluate(with: password)
        }
    }

我想知道电子​​邮件验证中有什么问题,如何使用密码验证?

提前致谢

2 个答案:

答案 0 :(得分:0)

怎么样?

func isEmailAddress() -> Bool {
        let regex = try! NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,}",
            options: [.CaseInsensitive])

        return regex.firstMatchInString(self, options:[],
            range: NSMakeRange(0, utf16.count)) != nil
}

将其应用为字符串扩展名,以便您可以使用此

验证任何其他字符串
let stringCandidate = "your email here"
if stringCandidate.isEmailAddress() {
    //is this what you need?
}

对于密码,只需像之前一样为字符串创建另一个扩展函数,并用正则表达式替换模式

答案 1 :(得分:0)

导入UIKit

类ViewController:UIViewController,UITextFieldDelegate {

@IBOutlet var registerTF: [KaustabhTF]!


// MARK:-  App LifeCycle

override func viewDidLoad() {

    super.viewDidLoad()
}


override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(animated)
}


override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)
}


override func viewWillDisappear(_ animated: Bool) {

    super.viewWillDisappear(animated)
}


override func viewDidDisappear(_ animated: Bool) {

    super.viewWillDisappear(animated)
}


override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()
}


// MARK:- User Defined

func nextTextFieldToFirstResponder(textField: KaustabhTF) {

    let senderTag = textField.tag


    if textField.absoluteCount() == 0
    {
        let alertController = UIAlertController(title: "Alert!!", message: "Please Enter the value here", preferredStyle: UIAlertControllerStyle.alert)

        alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))

        self.present(alertController, animated: true, completion: nil)

    }

    else
    {
        registerTF[senderTag + 1].becomeFirstResponder()
    }


    if senderTag == 0           // Name
    {

    }

    else if senderTag == 1      // Email
    {



    }

    else if senderTag == 2  // Password
    {


    }

    else if senderTag == 3 // Confirm Password
    {

    }





    /*if senderTag == (registerTF.count - 1)
    {
        textField.resignFirstResponder()
    }

    else
    {
        registerTF[senderTag + 1].becomeFirstResponder()

    }*/


}


// MARK:- IBAction

@IBAction func registerB(_ sender: Any) {

    let email = registerTF[1].text

    if(email?.isEmpty)!{
        print("Email left empty")
    }
    else
    {
        if(isValidEmail(email: email!))
        {
            print("Valid email")
        }
        else
        {
            print("Email is invalid")
        }
    }

    let password = registerTF[2].text

    let Cpassword = registerTF[3].text

    if(password?.isEmpty)!
    {
        print("Password left empty")
    }
    else
    {
        if(isValidPassword(pass: password))
        {

            if(Cpassword?.isEmpty)!
            {
                print("Confirmation password is required")
            }
            else
            {
                if(password == Cpassword)
                {
                    print("Password matches with each other")
                }
                else
                {
                    print("Passwords do not match with each other")
                }
            }
        }
        else
        {
            print("Passwords must have 8 charachters with atleast one uppercase, one lowercase and one number")
        }
    }




}

// MARK:- Email Validation Delegate

func  isValidEmail(email: String) -> Bool {

    let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[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])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"

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

    let result = emailTest.evaluate(with: email)

    return result

}

//MARK:- Password Validation


func isValidPassword(pass:String?) -> Bool {

    // at least one uppercase,
    // at least one digit
    // at least one lowercase
    // 8 characters total
    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}")

    return passwordTest.evaluate(with: pass)
}

// MARK:- TextField Delegate

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    self.nextTextFieldToFirstResponder(textField: textField as! KaustabhTF)

    return true
}

}