How
to validate a phone number (NSString *) in objective-c?
Rules:
- minimum 7
digits - maximum 10
digits - the first digit must be 2, 3, 5, 6, 8 or
9
Thanks
Answer
You can use a regular expressions library
(like RegexKit, etc), or you could use regular expressions through
NSPredicate
(a bit more obscure, but doesn't require
third-party libraries). That would look something like
this:
NSString *phoneNumber =
...;
NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",
phoneRegex];
BOOL matches = [test
evaluateWithObject:phoneNumber];
If
you're on iPhone, then iOS 4 introduced NSRegularExpression
,
which would also work. The NSPredicate
approach works on both
Mac and iPhone (any version).
No comments:
Post a Comment