Reputation: 7022
Im doing a conditional statement that checks if a textfield contains certain characters, if it does they an UIAlertView will show. At the moment if the text field contains letters then an the alert is shown, how would I extend my method below to include characters such as ? ! , $ etc.
if ([self.withdrawTextField.text rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Ooops" message:@"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
Upvotes: 1
Views: 663
Reputation: 14834
Try this:
NSMutableCharacterSet *mcs1 = [[NSCharacterSet letterCharacterSet] mutableCopy];
[mcs1 addCharactersInString:@"?!.$"];
if ([self.withdrawTextField.text rangeOfCharacterFromSet:mcs1].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Ooops" message:@"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
Upvotes: 2
Reputation: 5886
As you want only numbers and dot in the string than you can try below code. It may help you.
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
for (int i = 0; i < [[self.withdrawTextField.text length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Ooops" message:@"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}
Upvotes: 0