如何使用8到15个字符和强密码验证文本字段

I'm*_*ner 1 iphone validation uitextfield ios

我有一个文本字段,我想输入密码.我想输入强密码.这意味着8到15个字符,其中至少有一个小写字母,一个大写字母,1个空格字符,一个数字.请给出建议.

Mar*_*arc 5

password.length
Run Code Online (Sandbox Code Playgroud)

你可以要求字符串的长度.将其与您想要的限制进行比较.

- (BOOL)string:(NSString *)text matches:(NSString *)pattern
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];

    NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, text.length)];

    return matches.count > 0;
}
Run Code Online (Sandbox Code Playgroud)

你有一个方法为字符串提供正则表达式(你也可以将其作为NSString的类别实现).

第一个参数是你的密码,第二个参数是模式.

我对正则表达式不太好,所以可能有更好的解决方案,但这将是我的方式

NSString *password = @"iS_bhd97zAA!";
NSString *scPattern = @"[a-z]";
NSString *cPattern = @"[A-Z]";
NSString *sPattern = @"[!%&\._;,]";
NSString *nPattern = @"[0-9]";

if (8 <= password.length && password.length <= 15 &&
    [self string:password matches:scPattern] &&
    [self string:password matches:cPattern] &&
    [self string:password matches:sPattern] &&
    [self string:password matches:nPattern]) 
{
    NSLog(@"PW is valid");
}
Run Code Online (Sandbox Code Playgroud)

暗示

特殊字符的正则表达式很棘手,因为你需要逃避一些字符.我的可能是正确的,但我并不完全确定.

在一个正则表达式中也有可能做到这一点,但这看起来很可怕

这个

 (?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$
Run Code Online (Sandbox Code Playgroud)

拥有除了特殊字符之外的所有内容,也许你想自己添加:D