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.
- Atleast one numeric value and Atleast one alphabet should be present for the password
- Minimum 6 Maximum 32开发者_开发百科 characters should be allowed.
-(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.
Try this:
^(?=.*\d)(?=.*[A-Za-z]).{6,32}$
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");
}
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) :)
The following should meet the minimum/max characters, at least 1 alpha and 1 numeric character requirements:
^(?=.{6,32}$)(?=.*\d)(?=.*[a-zA-Z]).*$
精彩评论