Tuesday, March 25, 2014

iOS Email, Phone, and Credit Card Number Regex

-(BOOL)checkCellFormatting:(NSString* )phoneNumber
{
    
    NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    BOOL matches = [test evaluateWithObject:phoneNumber];
    
    return matches;
}

-(BOOL)checkEmailFormatting:(NSString* )emailAddress
{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL matches = [test evaluateWithObject:emailAddress];
    
    return matches;
}

-(BOOL) isCreditCardValid:(NSString*)creditCardNumber
{
    
    
    NSString *creditCardRegex = @"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", creditCardRegex];
    BOOL matches = [test evaluateWithObject:creditCardNumber];
        
    return matches;
        
}

-(BOOL) isCCVValid:(NSString*)ccvNumber
{
    

    
    NSString *ccvRegex = @"/^[0-9]{3,4}$/";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ccvRegex];
    BOOL matches = [test evaluateWithObject:ccvNumber];
    
    return matches;
    
}


-(BOOL) isExpirationDateValid:(NSString*)expirationDate
{
    
    
    NSString *expirationDateRegex = @"(1[2-9]|[2-9][0-9])(0[1-9]|1[0-2])";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", expirationDateRegex];
    BOOL matches = [test evaluateWithObject:expirationDate];
    
    return matches;

}

No comments:

Post a Comment