【问题标题】:textField Maximum length and Postal Code validationtextField 最大长度和邮政编码验证
【发布时间】:2020-05-06 16:19:36
【问题描述】:

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

【问题讨论】:

    标签: swift validation uitextfield textfield uitextfielddelegate


    【解决方案1】:

    如果我们将单个字符传递给函数validZipCode,它将始终返回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
                }
            }
    
        }
    

    希望这会有所帮助!!

    【讨论】:

    • 这很棒。谢谢!你怎么能让邮政编码在第三个字符后包含一个空格?所以当你在那里输入时,结果看起来像XXX XXX,总共是 7 个,第四个总是一个空格
    • 您可以将委托方法修改为, if textField == postalCodeTextField { // 将它们的新文本添加到现有文本中 let updatedText = currentText.replacingCharacters(in: stringRange, with: string) if(currentText .count == 3){ postalCodeTextField.text = postalCodeTextField.text! + " " } // 确保结果小于 7 个字符 return updatedText.count
    • 我确实做到了;但问题是当我尝试退格和删除时;一旦到达字符 3,它就不允许用户进一步删除,因为 character.count 从 4 变为 3 - 这里是说在 3 个字符处放置一个空格,使其变为 4 个字符
    • 好的,所以我使用这个解决方案来检测我们是否在退格,在这种情况下我不输入空格。否则我放空间:stackoverflow.com/questions/29504304/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2018-07-21
    • 2014-09-08
    相关资源
    最近更新 更多