Rahul Anand Rahul Anand - 2 months ago 15
iOS Question

Using `textField:shouldChangeCharactersInRange:`, how do i found that characters are mismatch?

I'm using the code below for setting validation of textfield as it should not enter above 15 character length .

let limitLength = 15

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

// set maximum length for password and confirm password
if textField == txtPassword { // if textfield password is editing

guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength

} else if textField == txtConfirmpassword { // if textfield confirm password is editing
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
return true
}


there are two textfield as password and confirm password
i want to check validation whether they have same string or not?

"textField:shouldChangeCharactersInRange" is method we need to use but i don't know how to compare while user is entering and i need to display alert message that they are not same
Note :- it should not compare while click on any button.

Answer

try like this

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

// set maximum length for password and confirm password
if textField == txtPassword { // if textfield password is editing

    guard let text = textField.text else { return true }
    let newLength = text.characters.count + string.characters.count
    return newLength <= limitLength

} else if textField == txtConfirmpassword { // if textfield confirm password is editing
    guard let text = textField.text else { return true }
    let newLength = text.characters.count + string.characters.count
    if newLength <= limitLength && txtPassword.text.hasPrefix("\(text)\(string)") {
    return true
} else {
   // here u can show alert
     textField.resignFirstResponder()
     return false
 }
      }
        return true
   }