如何使用textfield()函数快速检查我的文本字段的所有验证

时间:2018-09-02 16:03:00

标签: swift

所以我有一个问题,我想检查我的文本字段的验证。如果验证已经正确,则将启用该按钮,如果验证不正确,则将禁用该按钮。 问题是如果我已经通过了一个文本字段的验证并想移到另一个文本字段。验证仅检查我单击的文本字段的验证。如果我不纠正验证并转到另一个文本字段,则应禁用该按钮,如果我更正另一个文本字段的验证,该按钮将被启用。我要检查我所有文本字段的所有验证

我的代码中的

电子邮件是可选的 这是我的代码

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

    let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

    // Casting String as NSString to be able to replace characters using NSRange easily.
    guard let text = textField.text as NSString? else { return true }

    // Get the length of the final text
    let finalTextCount = text.replacingCharacters(in: range, with: string).count

    // Setup the text count for the field depending on which one was edited
    let nomorTextFieldCount = textField == nomorTextField ? finalTextCount :
        nomorTextField.text!.count

    let emailTextFieldCount = textField == emailTextFeild ? finalTextCount :
        emailTextFeild.text!.count
    if let floatingLabelTextField = textField as? SkyFloatingLabelTextField {
        nomorTextField.tag=1
        emailTextFeild.tag=2


        if textField.tag==1{

            if nomorTextFieldCount == 0 {
                floatingLabelTextField.errorMessage = "Nomor can't empty"
                nextButton.isEnabled = false

            }else if nomorTextFieldCount < 10   {
                floatingLabelTextField.errorMessage = "Nomor can't less than  10"
                nextButton.isEnabled = false

            }else if (nomorTextFieldCount > 12 ) {
                floatingLabelTextField.errorMessage = "Nomor can't more than 12"
                nextButton.isEnabled = false

            }

            else {
                floatingLabelTextField.errorMessage = ""
                nextButton.isEnabled = true

            }
        }else if textField.tag==2{
            if emailTextFieldCount == 0 {
                floatingLabelTextField.errorMessage = ""
                nextButton.isEnabled = true

            }
            else if emailTextFeild.text?.isEmail == false {
                floatingLabelTextField.errorMessage = "email format wrong"
                nextButton.isEnabled = false

            }else {
                floatingLabelTextField.errorMessage = ""
                nextButton.isEnabled = true

            }
        }
    }
    return true

}

0 个答案:

没有答案