ipraba
ipraba

Reputation: 16553

Regular Expression For Password in iPhone?

I am pretty much weak in creating Regular Expression. So I am here.

I need a regular expression satisfying the following.

  1. Atleast one numeric value and Atleast one alphabet should be present for the password
  2. Minimum 6 Maximum 32 characters should be allowed.

Upvotes: 4

Views: 5894

Answers (5)

Rayfleck
Rayfleck

Reputation: 12106

 -(BOOL) isPasswordValid:(NSString *)pwd {
     if ( [pwd length]<6 || [pwd length]>32 ) return NO;  // too long or too short
     NSRange rang;
     rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
     if ( !rang.length ) return NO;  // no letter
     rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
     if ( !rang.length )  return NO;  // no number;
     return YES;
 }

This is clearly not a regex, but imo regex is overkill for this.

Upvotes: 18

Oleks
Oleks

Reputation: 32343

Try this:

^(?=.*\d)(?=.*[A-Za-z]).{6,32}$

Upvotes: 10

Kris Babic
Kris Babic

Reputation: 6304

The following should meet the minimum/max characters, at least 1 alpha and 1 numeric character requirements:

^(?=.{6,32}$)(?=.*\d)(?=.*[a-zA-Z]).*$

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46965

Without using any third party libraries like Regexkit you can check for your requirements like so:

    if ([[password rangeOfCharacterFromSet: [ NSCharacterSet alphanumericCharacterSet]] &&
         [password rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @"0123456789"]] && 
        (6 < [password length]) && [password length] < 32)) {
              NSLog(@"acceptable password");
        }

Upvotes: 2

ArtoAle
ArtoAle

Reputation: 2977

Here you can find a usefull regexp cheatsheet wich also provide some examples. One of these is really similar to your needs (the 6th in the "Sample pattern box) :)

Upvotes: 1

Related Questions