Phanindra
Phanindra

Reputation: 57

How to avoid alphabet and special characters in a UITextfield?

I am formatting a US mobile number in a UITextfield.
I was done displaying the US number format, but it allows alphabet and special characters, including symbols.

I don't want allow alphabet and special characters.
How can I avoid these unwanted characters?

Please give any examples.

Upvotes: 0

Views: 1032

Answers (2)

iAnurag
iAnurag

Reputation: 9346

Try this

#define ACCEPTABLE_CHARACTERS @" Replace with what you want to be allowed."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:  (NSRange)range replacementString:(NSString *)string  {
  NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];

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

  return [string isEqualToString:filtered];

}

Upvotes: 1

Sanjay Mohnani
Sanjay Mohnani

Reputation: 5967

Please refer below link which fulfills your requirement of displaying and accepting only numeric values in UITextFiled -

http://hugolarcher.com/uitextfield-allowing-only-decimal-characters/

Upvotes: 0

Related Questions