如何使用SkyFloatingLabelTextField在swift中验证textField

时间:2017-03-10 05:01:41

标签: ios swift textfield skyfloatinglabeltextfield

  

我正在使用SkyFloatingLabeltextField作为textfield。我想检查所有文本字段是否有效然后我想调用下一个viewController.So请告诉我如何检查func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}

     

是真还是不?   以下是我的代码

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {


    if let text = username.text {

        let message = Comman.matches(for: "[a-zA-Z]+[0-9a-zA-Z._%+-]+[a-zA-Z0-9]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{1,6}", in: text)

        print(message.count);
        print(message)
        if let floatingLabelTextField = username as? SkyFloatingLabelTextField {
            if(message.count != 1) {
                floatingLabelTextField.errorMessage = "Please enter valid email id"
            }
            else {
                // The error message will only disappear when we reset it to nil or empty string
                floatingLabelTextField.errorMessage = ""
            }

        }
    }

    if let text = password.text {

        let message = Comman.matches(for: "^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&])(?=.*\\d).{8,16}$", in: text)

        if let floatingLabelTextField = password as? SkyFloatingLabelTextField {
            if(message.count != 1) {
                floatingLabelTextField.errorMessage = "Please enter valid Password"
            }
            else {
                // The error message will only disappear when we reset it to nil or empty string
                floatingLabelTextField.errorMessage = ""
            }

        }
    }

    if let text = firstName.text {
        let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")

        if let floatingLabelTextField = firstName as? SkyFloatingLabelTextField {
        if text.rangeOfCharacter(from: characterset.inverted) != nil {
            floatingLabelTextField.errorMessage = "Please enter valid Name"
        }
        else {
                // The error message will only disappear when we reset it to nil or empty string
                floatingLabelTextField.errorMessage = ""
            }

        }
    }

    if let text = lastName.text {
        let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")

        if let floatingLabelTextField = lastName as? SkyFloatingLabelTextField {
            if text.rangeOfCharacter(from: characterset.inverted) != nil {
                floatingLabelTextField.errorMessage = "Please enter valid Name"
            }
            else {
                // The error message will only disappear when we reset it to nil or empty string
                floatingLabelTextField.errorMessage = ""
            }

        }
    }
    if let text = mobileNumber.text {
        let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")

        if let floatingLabelTextField = mobileNumber as? SkyFloatingLabelTextField {
            if text.rangeOfCharacter(from: characterset.inverted) != nil {
                floatingLabelTextField.errorMessage = "Please enter valid Mobile number"
            }
            else {
                // The error message will only disappear when we reset it to nil or empty string
                floatingLabelTextField.errorMessage = ""
            }

        }
    }

    return true
}
  

和我的按钮一样

    @IBAction func signUpButtonPressed(_ sender: Any) {  if username.text == "" {
         if let floatingLabelTextField = username as? SkyFloatingLabelTextField {
             floatingLabelTextField.errorMessage = "Please enter UserName"
        }
    }
    if password.text == "" {
        if let floatingLabelTextField = password as? SkyFloatingLabelTextField {
            floatingLabelTextField.errorMessage = "Please enter Password"
        }
    }

    if firstName.text == "" {
        if let floatingLabelTextField = firstName as? SkyFloatingLabelTextField {
            floatingLabelTextField.errorMessage = "Please enter First Name"
        }
    }
    if lastName.text == "" {
        if let floatingLabelTextField = lastName as? SkyFloatingLabelTextField {
            floatingLabelTextField.errorMessage = "Please enter Last Name"
        }
    }
    if mobileNumber.text == "" {
        if let floatingLabelTextField = mobileNumber as? SkyFloatingLabelTextField {
            floatingLabelTextField.errorMessage = "Please enter Mobile Number"
        }
    }

}

  

那么当它有效时如何处理????

2 个答案:

答案 0 :(得分:4)

在这种情况下,您需要实现UITextfield的委托:

如果要检查每个字符输入并希望控制文本输入,请使用以下方法:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == newPasswordTextField {
        let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
        let existOrNotNumber  = checkTextNumber(text: newString)
        let existOrNotSpecialCharacter  = checkSpecialCharacter(text: newString)
        let existOrNotCapitalCharacter = CapitalLetter(text: newString)
        let existOrNotlwerCharacter = lowerCaseLetter(text: newString)
        let usernameSameOrNot = checkUserName(text: newString )

        textField.text = newString;

        if existOrNotNumber {
            numericDigitLabel.textColor = kGreenColor
        }else{
            numericDigitLabel.textColor = UIColor.red
        }
        if existOrNotSpecialCharacter {
            specialCharacterLabel.textColor = kGreenColor
        }else{
            specialCharacterLabel.textColor = UIColor.red
        }
        if existOrNotCapitalCharacter{
            uppercaseCharacterLabel.textColor = kGreenColor
        }else{
            uppercaseCharacterLabel.textColor = UIColor.red
        }
        if existOrNotlwerCharacter{
            lowercaseCharacterLabel.textColor = kGreenColor
        }else{
            lowercaseCharacterLabel.textColor = UIColor.red
        }
        if (newString.characters.count) >= 8 && (newString.characters.count) <= 50 {
            minimumEightCharacterLabel.textColor = kGreenColor
        }else{
            minimumEightCharacterLabel.textColor = UIColor.red
        }
        if usernameSameOrNot{
         userNameCannotBePasslabel.textColor = kGreenColor
        }else{
         userNameCannotBePasslabel.textColor = UIColor.red
        }
        return false
    }
    return true
}

您可以在此检查每个文字验证。为了验证我创建了这个通用函数来验证。

// MARK: - Validation for  Textfield

func isValidAllFields() -> Bool {
    var isValid = true
    var errorMessage : String = ""
    let showAndReturn : () -> Bool = { Void -> Bool in
        AppUtility.showAlert(message: errorMessage, isSuccess: false)
        return isValid
    }

    let showAndReturnWithoutToast : () -> Bool = { Void -> Bool in
        return isValid
    }

    if (oldPasswordTextField.text ?? "").isEmpty || (oldPasswordTextField.text?.trimmingCharacters(in: .whitespaces).characters.count)! == 0  {
        isValid = false
        errorMessage = kOldPasswordEmptyMessage
        return showAndReturn()
    }

    if (newPasswordTextField.text ?? "").isEmpty || (newPasswordTextField.text?.trimmingCharacters(in: .whitespaces).characters.count)! == 0  {
        isValid = false
        errorMessage = kNewPasswordEmptyMessage
        return showAndReturn()
    }

    if (confirmPasswordTextField.text ?? "").isEmpty || (confirmPasswordTextField.text?.trimmingCharacters(in: .whitespaces).characters.count)! == 0  {
        isValid = false
        errorMessage = kConfirmPasswordEmptyMessage
        return showAndReturn()
    }

    if oldPasswordTextField.text != UserDefaults.standard.object(forKey: kOldPassword) as? String {
        isValid = false
        errorMessage = kCorrectOldPasswordMessage
        return showAndReturn()
    }

    if  (newPasswordTextField.text?.characters.count)! < 8 || (newPasswordTextField.text?.characters.count)! > 50 {
        isValid = false
        return showAndReturnWithoutToast()
        // errorMessage = "New password should not be less than 8 characters and more than 50 characters"
    }

    if !checkTextNumber(text: newPasswordTextField.text!) {
         isValid = false
         return showAndReturnWithoutToast()
         // errorMessage = "New password must contain at least 1 Numeric digit"
    }

    if !checkSpecialCharacter(text: newPasswordTextField.text!) {
        isValid = false
        return showAndReturnWithoutToast()
        // errorMessage = "New password must contain at least 1 special character"
    }

    if !CapitalLetter(text: newPasswordTextField.text!) {
        isValid = false
        return showAndReturnWithoutToast()
        //errorMessage = "New password must contain at least 1 Upper case character"
    }

    if !lowerCaseLetter(text: newPasswordTextField.text!) {
        isValid = false
        return showAndReturnWithoutToast()
        // errorMessage = "New password must contain at least 1 Lower case character"
    }

    if !checkUserName(text: newPasswordTextField.text!) {
        isValid = false
        return showAndReturnWithoutToast()
    }

    if confirmPasswordTextField.text != newPasswordTextField.text{
        isValid = false
        errorMessage = kNewPassAndCofirmSameMessage
        return showAndReturn()
    }
    return isValid
}

on Button单击只检查isValid(),如果返回true则允许它传递给下一个视图控制器

答案 1 :(得分:0)

如果要在键入时执行检查,可以使用委托方法执行检查:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let text = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
    // Perform validation of the `text`
    if valid {
        return true
    } else {
        return false
    }
}

或者,如果您想在填写完所有字段后执行检查,您只需按textField.text检查文字。