textField 最大长度和邮政编码验证

textField Maximum length and Postal Code validation

我有一个用于输入加拿大邮政编码的文本字段。我正在使用以下代码来确保格式正确,否则会显示一条警告,说明格式不正确。这在 saveBtnClick 上没有问题;但我无法在该字段中键入内容,因为它继续将 false 返回到文本字段中,因为 validZipCode function.I 还需要确保该字段的最大字符长度不超过 7 个字符,所以用户不能键入超过七个字符。我看到许多解决方案仅用于设置最大长度;但无法弄清楚如何使用我在此处提到的用于邮政编码验证的现有条件来执行此操作。这是我当前的代码:

@IBOutlet weak var postalCodeTextField: UITextField!

override func viewDidLoad() {
    phoneNumberTextField.delegate = self
    postalCodeTextField.delegate = self
}

func validZipCode(postalCode:String)->String{
    let postalcodeRegex = "^[a-zA-Z][0-9][a-zA-Z][- ]*[0-9][a-zA-Z][0-9]$"
    let pinPredicate = NSPredicate(format: "SELF MATCHES %@", postalcodeRegex)
    let bool = pinPredicate.evaluate(with: postalCode) as Bool
  return bool.description
}

@IBAction func saveBtnClicked(_ sender: Any) {

    let isPostalCodeValid = validZipCode(postalCode: postalCodeTextField.text ?? "")

    if isPostalCodeValid == "false" {

        simpleAlert(title: "Error!", msg: "Please enter a valid CA postal code")

    } else
        if isPostalCodeValid == "true" {
       //the postalCaode is correct formatting
    }

}




func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else { return false }
        let newString = (text as NSString).replacingCharacters(in: range, with: string)

    if textField == phoneNumberTextField {
        textField.text = formattedNumber(number: newString)
    } else

        if textField == postalCodeTextField {
            textField.text = validZipCode(postalCode: newString)
    }

    return false
}

函数 validZipCode 如果我们向它传递单个字符,它总是 return false。因此,在单击 saveButton 时验证谓词。

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var postalCodeTextField: UITextField!

       override func viewDidLoad() {
            postalCodeTextField.delegate = self
        }

        func validZipCode(postalCode:String)->Bool{
              let postalcodeRegex = "^[a-zA-Z][0-9][a-zA-Z][- ]*[0-9][a-zA-Z][0-9]$"
            let pinPredicate = NSPredicate(format: "SELF MATCHES %@", postalcodeRegex)
            let bool = pinPredicate.evaluate(with: postalCode) as Bool
            return bool
        }

        @IBAction func saveBtnClicked(_ sender: Any) {

            let isPostalCodeValid = validZipCode(postalCode: postalCodeTextField.text ?? "")

            if isPostalCodeValid == false {
                print("false")
               // simpleAlert(title: "Error!", msg: "Please enter a valid CA postal code")

            } else
                if isPostalCodeValid == true {
                    print("true")
               //the postalCaode is correct formatting
            }

        }

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

            let currentText = textField.text ?? ""
             guard let stringRange = Range(range, in: currentText) else { return false }

            if textField == postalCodeTextField {
                // add their new text to the existing text
                let updatedText = currentText.replacingCharacters(in: stringRange, with: string)

                // make sure the result is under 7 characters
                return updatedText.count <= 7
            }else{
                return true
            }
        }

    }

希望对您有所帮助!!