vivek bhoraniya
vivek bhoraniya

Reputation: 1535

Error in defining validation string

I have written code to validate US zip code...but it is giving me error that unknown escape sequence \d which is in validation string. Code:

- (BOOL)zipcodevalidation:(NSString *)zipstring {

    NSString *emailRegex = @"(^\d{5}(-\d{4})?$)";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:zipstring];
}

Upvotes: 0

Views: 66

Answers (2)

Deepesh
Deepesh

Reputation: 8053

try this for US Zip code valiadtion

- (BOOL)zipcodevalidation:(NSString *)zipstring {

    NSString *emailRegex = @"(^[0-9]{5}(-[0-9]{4})?$)";


    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:zipstring];
}

Upvotes: 0

Paul.s
Paul.s

Reputation: 38728

You need to escape the backslashes so that the string does not interpreted them as escape sequences that are used in strings like \t, \n etc

@"(^\\d{5}(-\\d{4})?$)";

Upvotes: 2

Related Questions