Reputation: 342
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
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
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
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