首页 > 解决方案 > textField 最大长度和邮政编码验证

问题描述

我有一个文本字段来输入加拿大邮政编码。我正在使用以下代码来确保格式正确,否则会显示一个警告,指出格式不正确。这在saveBtnClick;上没有问题。但由于该功能,我无法输入该字段,因为它继续返回false到 textField。我validZipCode还需要确保该字段的最大字符长度不超过 7 个字符,因此用户不能输入超过 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
}

标签: swiftvalidationuitextfieldtextfielduitextfielddelegate

解决方案


The function validZipCode would always return false if we pass single character to it. So ,validate the predicate on click of 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
            }
        }

    }

Hope this helps !!


推荐阅读