Created
July 17, 2014 06:02
-
-
Save bennythemink/ec7bf376c280b2cf1dd1 to your computer and use it in GitHub Desktop.
Small but handy NSString extension for checking if the string is a valid email address or is a valid number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NSString (Extension) | |
- (BOOL) isAnEmail; | |
- (BOOL) isNumeric; | |
@end | |
@implementation NSString (Extension) | |
/** | |
* Determines if the current string is a valid email address. | |
* | |
* @return BOOL - True if the string is a valid email address. | |
*/ | |
- (BOOL) isAnEmail | |
{ | |
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; | |
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; | |
return [emailTest evaluateWithObject:self]; | |
} | |
/** | |
* Determines if the current NSString is numeric or not. It also accounts for the localised (Germany for example use "," instead of ".") decimal point and includes these as a valid number. | |
* | |
* @return BOOL - True if the string is numeric. | |
*/ | |
- (BOOL) isNumeric | |
{ | |
NSString *localDecimalSymbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator]; | |
NSMutableCharacterSet *decimalCharacterSet = [NSMutableCharacterSet characterSetWithCharactersInString:localDecimalSymbol]; | |
[decimalCharacterSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]]; | |
NSCharacterSet* nonNumbers = [decimalCharacterSet invertedSet]; | |
NSRange r = [self rangeOfCharacterFromSet: nonNumbers]; | |
if (r.location == NSNotFound) | |
{ | |
// check to see how many times the decimal symbol appears in the string. It should only appear once for the number to be numeric. | |
int numberOfOccurances = [[self componentsSeparatedByString:localDecimalSymbol] count]-1; | |
return (numberOfOccurances > 1) ? NO : YES; | |
} | |
else return NO; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment