user1478583
user1478583

Reputation: 342

how to use regular expression in iOS sdk

How to use regular expression in iOS sdk?

I need to validate UITextField using regular expression allow only numerical values into UITextField.

Upvotes: 2

Views: 4718

Answers (4)

Ab'initio
Ab'initio

Reputation: 5418

Call this method where you need.it returns true if checkString contains only numerals

- (BOOL) textFieldValidation:(NSString *)checkString {
       NSString *stricterFilterString = @"[0-9]+";//here + is for one or more numerals(use * for zero or more numerals)
       NSString *regEx =  stricterFilterString;
       NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
       return [emailTest evaluateWithObject:checkString];

}

Upvotes: 0

Ravi
Ravi

Reputation: 1759

Try this, it would be helpfull to you

- (void)textFieldDidEndEditing:(UITextField *)textField 
{
    activeField = nil;
    if (textField == tfMobile) 
    {
        NSString *strRegExp=@"[0-9]*";
        NSPredicate *MobNumTest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",strRegExp];
        if([MobNumTest evaluateWithObject:textField.text]==NO)
        { 

            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Please Enter correct contact no." delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];

            [alert show];
            [alert release];

            tfMobile.text =@"";

        }

    }
    }

Upvotes: 1

Mihir Mehta
Mihir Mehta

Reputation: 13833

In your shouldChangeCharactersInRange you can do it by this

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

        NSString *expression = @"^([0-9]+$";

        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression 
                                                                               options:NSRegularExpressionCaseInsensitive 
                                                                                error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                            options:0
                                                              range:NSMakeRange(0, [newString length])];        
        if (numberOfMatches == 0)
            return NO;        


    return YES;
}

Upvotes: 3

kiran
kiran

Reputation: 4409

Try this for your regular expression ^[0-9]+$

Upvotes: 2

Related Questions