Check if NSString contains any numbers and is at least 7 characters long Check if NSString contains any numbers and is at least 7 characters long ios ios

Check if NSString contains any numbers and is at least 7 characters long


While a regular expression would probably work, there is another approach:

NSString *str = // some string to check for at least one digit and a length of at least 7if (str.length >= 7 && [str rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != NSNotFound) {    // this matches the criteria}

This code actually checks more than just 0-9. It handles digits from other languages too. If you really just want 0-9 then replace:

[NSCharacterSet decimalDigitCharacterSet]

with:

[NSCharacterSet characterSetWithCharactersInString:@"0123456789"];