UITextField - Allow only numbers and punctuation input/keypad
Asked Answered
E

4

9

I have tried the code below but that only allows for numbers on the keypad to be inputted. My app requires the keypad to use a period/full stop (for money transactions). The code I tried is:

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

   NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

     if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound)
      {
         return NO;
    }
   return YES;

}

Thanks for any help.

Exegesis answered 21/11, 2013 at 13:35 Comment(3)
set your text field to: [textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];Vesicatory
@Vesicatory this does not prevent the user from changing to the ABC keyboard.Exegesis
Answered a similar question here.Brindabrindell
D
44

Try this

Make a macro

#define ACCEPTABLE_CHARACTERS @"0123456789."

And use it

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

    if (textField==textFieldAmount)
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return [string isEqualToString:filtered];
    }
    return YES;
}
Diecious answered 21/11, 2013 at 13:39 Comment(2)
Thanks, whats textFieldAmount?Exegesis
I have mulitiple textfield thats y i am checking.Diecious
N
3

In Swift 3:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = "0123456789!@#$%^&*()_+~:{}|\"?><\\`,./;'[]=-"
    return allowedCharacters.contains(string) || range.length == 1
}
Norvol answered 28/10, 2016 at 19:36 Comment(1)
@SPatel Also the question is "allow only punctuation and numbers". . is punctuationNorvol
C
2

Just use

[textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];

after creating your textfield.

Consecution answered 21/11, 2013 at 13:38 Comment(3)
this does not prevent the user from changing to the ABC keyboard.Exegesis
@Gman Well I guess there is no standard keyboard that fully meets your requirements... I guess you'd have to make your own input view for that purpose though that seems like an overkill to me.Consecution
It also doesn't defend from pasting incorrect data into a textFieldVilhelmina
A
2

How about a custom character set? Something like this:

NSCharacterSet *testChars = [NSCharacterSet characterSetWithCharactersInString:@"0123456789+*#-() "];

Because setting the keyboard type is pretty useless on iPad...

Adamson answered 21/11, 2013 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.