I’m trying to validate a Password Textfield in realtime (Swift 4.2 & Xcode 10.2.1).
My question is how to validate the conditions listed below in UITextField's shouldChangeCharactersInrange method?
- Minimum 8 characters
- Maximum 50 characters
- Minimum 1 alphabet
- Minimum 1 number
- No special characters
Also, there will be a gray color tick image on the left side of all 4 validation messages. As long as the condition are not met, image will be gray color tick. If validation succeeds, tick images will turn to green.
When I tap the Confirm button in the screen, I will have to call Set New Password API. I'm thinking about setting a bool isValidationSuccess to true when all the above conditions are met in shouldChangeCharactersInrange method.
On Confirm button tap, api will only be called if isValidationSuccess is true.
This is what I have managed so far. Could you please help me?
// MARK: - TextField delegate methods
extension SetNewPasswordViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
let minPasswordLength = 8
let currentString: NSString = newPasswordTextfield.text! as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
if newString.length < minPasswordLength {
minimumCharacterValidationImage.isHighlighted = false
} else {
minimumCharacterValidationImage.isHighlighted = true
}
return true
}
}
.replacingCharacters
if your method returns a Boolean? I think you may userange
, something like:return newPasswordTextfield.text.range(of: "^(?=\\D*\\d)(?=\\d*[A-Za-z])[A-Za-z0-9]{8,50}$", options: .regularExpression) != nil
– Wiktor Stribiżew