Regular Expresssion For Password in iPhone

大憨熊 提交于 2019-12-03 08:24:00
 -(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]).*$
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!