Password validation in UITextField in iOS

前端 未结 11 1117
有刺的猬
有刺的猬 2020-12-01 12:54

I have 1 UITextfield for password in my iPhone application.

I want to validate this textfield with the following validation.

  • Must be at le
11条回答
  •  旧时难觅i
    2020-12-01 13:19

    use a regex (NSRegularExpression class has docs on how to write the patten itself) and then :

    - (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        //delete
        if (string.length == 0) {
            return YES;
        }
    
        if (self.regEx) {
            NSMutableString* check = [NSMutableString stringWithString:theTextField.text];
            [check replaceCharactersInRange:range withString:string];
            NSTextCheckingResult* match = [self.regEx firstMatchInString:check options:0 range:NSMakeRange(0, [check length])];
            if (match.range.length != check.length) {
                return NO;
            }
        }
    }
    

    Warning: Restricting the input this way is really confusing for users. You type and type and the character you type just doesnt appear!

    I'd maybe go with a small red (!) next to the test field but I'd always allow the input itself!

提交回复
热议问题