RaviMalviya
4/19/2016 - 6:00 PM

RegEx Validation in ios


Example:

ViewController.m -----

    NSString *string = txt.text;
    
//    NSString *pattern = @"^[0-9a-zA-Z]{6,10}$";//For Single Word
//    NSString *pattern = @"[0-9a-zA-Z]";//For Every Charater
      NSString *pattern = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";//Email Validation
//    NSString *pattern = @"#{{[[[0-9]{1,10}-[0-9]{1,10}-[0-9]{1,10}]]}}";//Create Error
    
    BOOL decide = [SharedClass regexPattern:pattern String:string];

SharedClass.m -----

+(BOOL)regexPattern:(NSString *) pattern String:(NSString *) string  {

    NSInteger length = [string length];
    NSRange range = NSMakeRange(0, length);

    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:pattern
                                  options:NSRegularExpressionCaseInsensitive
                                  error:&error];
    if (error == nil) {
        NSArray *matches  = [regex matchesInString:string options:0 range:range];
        NSString *strFinal = @"";
        for (NSTextCheckingResult *textResult in matches) {
            NSString *substring = [string substringWithRange:textResult.range];
            strFinal = [NSString stringWithFormat:@"%@%@",strFinal,substring];
        }
        if ([string isEqualToString:strFinal]) {
            return true;
        }else{
            return false;
        }
    }else{
        //InValide Regex Error
        return true;//I need true you can put false.
    }
}