Reputation: 1213
InUITextBoxfield
,i insert some value,and I Want to use RegularExpressions match the string ..now i want the text box text should be match for only numeric digits upto 3 when I press button then it should work...
What I am trying is which is not working::-
-(IBAction)ButtonPress{
NSString *string =activity.text;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
if ([activity.text isEqualToString:modifiedString ])
{ // work only if this matches numeric value from the text box text
}}
Upvotes: 1
Views: 462
Reputation: 25318
Your code replaces all matches with an empty string, so if there is a match, it will be replaced by an empty string and your check will never work. Instead, just ask the regular expression for the range of the first match:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:NULL];
NSRange range = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if(range.location != NSNotFound)
{
// The regex matches the whole string, so if a match is found, the string is valid
// Also, your code here
}
You can also just ask for the number of matches, if it's not zero, the string contains a number between 0
and 999
because your regex matches for the whole string.
Upvotes: 2
Reputation: 20551
- (BOOL)NumberValidation:(NSString *)string {
NSUInteger newLength = [string length];
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return (([string isEqualToString:filtered])&&(newLength <= 3));
}
in your button action event just use this like bellow...
-(IBAction)ButtonPress{
if ([self NumberValidation:activity.text]) {
NSLog(@"Macth here");
}
else {
NSLog(@"Not Match here");
}
}
Upvotes: 2
Reputation: 16864
Please try following code.
- (BOOL) validate: (NSString *) candidate {
NSString *digitRegex = @"^[0-9]{1,3}$";
NSPredicate *regTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", digitRegex];
return [regTest evaluateWithObject:candidate];
}
-(IBAction)btnTapped:(id)sender{
if([self validate:[txtEmail text]] ==1)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Correct id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Incoorect id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}
}
Upvotes: 1