密码和电子邮件的文本字段验证

时间:2017-11-07 09:14:01

标签: swift3

我想分别为两个textfielfd实现文本字段验证,但是我无法这样做,我已经为两者提升了代理,但是它们被应用于两个文本字段,例如。电子邮件只接受10个字符我们如何单独为电子邮件和移动电话单独应用它不单独以下是我写的代码:

    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
        if textField == textfieldemail
                {
                    let providedEmailAddress = self.textfieldemail.text

                    let isEmailAddressValid = isValidEmailAddress(emailAddressString: providedEmailAddress!)

                    if isEmailAddressValid
                    {
                        print("Email address is valid")
                    }
                    else {

                        self.displayAlertMessage(messageToDisplay: "Email address is not valid")

                        }
                }
}

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

    let startingLength = textField.text?.characters.count ?? 0
    let lengthToAdd = string.characters.count
    let lengthToReplace =  range.length
    let newLength = startingLength + lengthToAdd - lengthToReplace
    return newLength <= charsLimit

}

1 个答案:

答案 0 :(得分:0)

您可以通过为textfield指定标记并检查其中的标记来唯一地标识文本字段。

UITextFieldDelegate分配给相应的ViewController

为textField

设置委托
emailIDTxtFld.delegate = self
mobileNoTxtFld.delegate = self

为textField设置标记

emailIDTxtFld.tag = 1001
mobileNoTxtFld.tag = 1002

现在实施这些方法

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

    if textField.tag == 1002{
    //For MobileNo it will accept only 10 char
        if newString.characters.count > 10{
            return false
        }else{
            return true
        }
    }else if textField.tag == 1002{
     //your logic
    }
    return true
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField.tag == 1001{
        if textField.isValidEmail(){
            // Code
        }else{
            print("Please Enter Vlaid Email ID")
        }

    }else if textField.tag == 1002{
        if textField.text?.characters.count == 10{
            // code
        }else{
            //code
        }
}