0

In my iOS project I want to validate the password ,where I should accept the password which is strictly alphanumeric,,i.e Passoword must contains both alphabets and Numbers , I have done this by the following method, But It is taking numbers as optional,, It looks simple but its eating my time,,pls help me out

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;
        }
vadian
  • 274,689
  • 30
  • 353
  • 361
Ravi Kiran
  • 691
  • 3
  • 9
  • 22

3 Answers3

3

You can do it.

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);

Result:

hRj4fg2* invalid

hRj4fg2 valid

shkdskd Invalid

1234545 Invalid

jam56h&jk Invalid

Jamil
  • 2,977
  • 1
  • 13
  • 23
3

Your code looks good, you should try with this pattern:

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

that ensures the input contains at-least an alphabet, and at-least a number, and only accepts alpha-numeric combination.

Regex Demo

Sample code:

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;
}

Hope it helps!

Community
  • 1
  • 1
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
2

use NSCharacterSet instead of regex,

    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
    }
Saif
  • 2,678
  • 2
  • 22
  • 38