iOS中密码字段的字母数字验证

时间:2015-11-02 07:08:25

标签: ios objective-c iphone regex nsregularexpression

在我的iOS项目中,我想要验证密码,我应该接受严格的字母数字密码,即Passoword必须包含字母和数字,我通过以下方法完成此操作,但它将数字视为可选,它看起来很简单,但它吃我的时间,请帮助我

NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[a-z0-9]*"
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        NSArray *matches = [regex matchesInString:input
                                          options:0
                                            range:NSMakeRange(0, [input length])];

        if([matches count] > 0)
        {
            // Valid input
            return true;
        }
        else
        {
            return false;
        }

3 个答案:

答案 0 :(得分:3)

您的代码看起来不错,您应该尝试使用此模式:

^(?=.*[a-z])(?=.*\d)[a-z\d]*$

确保输入至少包含一个字母,至少包含一个数字,并且只接受字母数字组合。

Regex Demo

示例代码:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(?=.*[a-z])(?=.*\\d)[a-z\\d]*$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];
NSArray *matches = [regex matchesInString:input
                                  options:0
                                    range:NSMakeRange(0, [input length])];

if([matches count] > 0)
{
    // Valid input
    return true;
}
else
{
    return false;
}

希望它有所帮助!

答案 1 :(得分:2)

使用NSCharacterSet代替正则表达式,

    private func containsOnlyNumbers(number:String)-> Bool
    {
        let numberCharSet = NSCharacterSet(charactersInString: "0123456789")
        let stringAfterRemovingNumbers = number.stringByTrimmingCharactersInSet(numberCharSet)
        return (stringAfterRemovingNumbers.characters.count==0)//string contains only numbers if it has zero charecters after removing numbers from it
    }

答案 2 :(得分:2)

你可以做到。

NSString *pass= @"hRj4fg2";
NSString    *regex     = @"^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]*$";//@"^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]*$";//Both will work
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isValidPassword = [predicate evaluateWithObject:pass];
NSLog(@"isValidPassword:%d",isValidPassword);

结果:

hRj4fg2 * 无效

hRj4fg2 有效

shkdskd 无效

1234545 无效

jam56h& jk 无效