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];

}
有帮助吗?

解决方案

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];

}

其他提示

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;
       }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top