How to avoid alphabet and special characters in a UITextfield? - ios

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.

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

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/

Related

add prefix to UITextField

I want to add prefix of UITextfield text. The UITextfield text length less than 7. How many characters are less than 7, that all replace with zeros.
If text is "1234", add prefix like "0001234".
If text is "12345", add prefix like "0012345".
If text is "123", add prefix like "0000123".
can any one suggest me, how to implement.
It sounds like what we actually want is a numbers-only string that is always 7-characters long, with the left-most characters filled in with padded zeros for anything the user has not entered, correct?
So, we need a handful of methods to make this as easy as possible.
First, this one doesn't make sense right now, but we want a method to remove the zeros we padded at the front (it'll make sense later).
So, borrowing from this Stack Overflow answer...
- (NSString *)stringByRemovingPaddedZeros:(NSString *)string {
NSRange range = [string rangeOfString:#"^0*" options:NSRegularExpressionSearch];
return [string stringByReplacingCharactersInRange:range withString:#""];
}
And we'll borrow from Ilesh's answer for adding the padded zeros:
- (NSString *)stringByAddingPaddedZeros:(NSString *)string padLength:(NSInteger)length {
NSString *padding = [#"" stringByPaddingToLength:(length - string.length) withString:#"0" startingAtIndex:0];
return [NSString stringWithFormat:#"%#%#", padding, string];
}
So now we can go back and forth between padded and unpadded strings, right?
So now, one last step, implementing shouldChangeCharactersInRange:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
newString = [self stringByRemovingPaddedZeros:newString];
newString = [self stringByAddedPaddedZeros:newString padLength:7];
textField.text = [newString subStringToIndex:7];
return NO;
}
We always return NO here, as we're setting the textField.text property manually. Now when there are 7 characters (and no leading zeros), the user can type no more. If there are 7 characters and the user hits backspace, they should all shift right one and a zero added to the front. If there are leading zeros at the front, typing characters should shift everything left and drop a leading zero, and add a new character to the front.
As an additional note, this code does not take care of verifying that the user is only entering digits. Some extra logic would be required for that. I'd simply recommend checking that the replacementString (string) is only digits before you get into any of the other code in shouldChangeCharactersInRange here.
Here printing textfield text on button click. Check the code inside the method.
- (IBAction)logTextFieldText:(id)sender
{
NSMutableString *str=[[NSMutableString alloc]init];
if (_txtf.text.length<7)
{
for (int i=0;i<7-_txtf.text.length; i++)
{
[str appendString:#"0"];
}
[str appendString:_txtf.text];
}
NSLog(#"final text is: %#",str);
}
Implement the UITextFieldDelegate method textFieldDidEndEditing: to pad the 0's in.
- (void)textFieldDidEndEditing:(nonnull UITextField *)textField
{
if (textField.text.length < 7) {
// Create a string of 0's to pad with
NSString *padding = [#"" stringByPaddingToLength:(7 - textField.text.length) withString:#"0" startingAtIndex:0];
NSMutableString *change = [textField.text mutableCopy];
// Insert the 0's string
[change insertString:padding atIndex:0];
textField.text = change;
}
}
If you want to fix the length of UITextField text than use this UITextField delegate method.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (self.txtGet.text.length>=7) {
return NO;
}
return YES;
}
and the completion editing (or done button ) you add this line in before using the UITextField value.
NSString *padding = [#"" stringByPaddingToLength:(7 - self.txtGet.text.length) withString:#"0" startingAtIndex:0];
NSMutableString *change = [self.txtGet.text mutableCopy];
// Insert the 0's string
[change insertString:padding atIndex:0];
self.txtGet.text = change;
I think its helpful to you. Thank you.

How do I enforce that an UITextView shows only lower-case letters? [duplicate]

This question already has answers here:
Converting all text to lower case in Objective-C
(3 answers)
Closed 7 years ago.
I'm working on a social script for iOS but i'll need my username login only be lowercase. I've got the string where lowercaseString needs to be into but I don't exactly know where.
So this is the code:
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];**
Where do I put the .lowercaseString for only lowercase login?
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].lowercaseString;
However, this only ensures that username is lowercase. To make sure that the UITextField contains only lowercase characters, you may do this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
NSRange upperCharRange;
upperCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];
if (uppercaseCharRange.location != NSNotFound) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string lowercaseString]];
return NO;
}
return YES;
}
This method is only called if you add <UITextFieldDelegate> to the .h file of your class. You also need to set the delegate of your UITextField instance to self of your class instance, like so:
textField.delegate = (id <UITextFieldDelegate>)mainViewController;
You can put it after self.usernameField.text or after the ]]. There is not really any difference since lowerCase does not affect whitespaces or newline characters.
The only difference is that after trimming the string, the string might be shorter and therefore the transformation to a lower case string will take less time (not noticeably though).
Therefore I would propose adding it after ]]:
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].lowercaseString;

Check the content of NSString with data in NSArray

I have the next problem:
In a UITextField, I need to check if the user inserts an invalid character for the Name, like [ ] { }.
My question is, how can I check the content of the UITextField with one NSArray with the invalid characters inside?
If you want to check single letter input from keyboard on some input politics
you need to use textField delegate method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
You should check if string contains in your exception array. If so you return NO and symbol doesn't appear on screen.
Ok, I explain what I do to solve the problem. Cause I'm controlling the behavior of a UITextField where I use to the user enter the name and one comment, I make a character set with all characters I allow and I put inside the shouldChangeCharactersInRange Method:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:#" ,.abcdefghijklmnopqrstuvwxyzçñ?!'ABCDEFGHIJKNMLOPQRSTUVWXYZÇÑ-_;:0123456789+*()-/#áàéèíìóòúù"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}

Allowing pasting of numbers only from an alphanumeric in a textfield

I want the textfield to allow the user to paste only numbers from the alphanumeric text and the same should be displayed.I have already dealt with the keypad part.I have tried the delegate method but it restricts the text altogether ,if it contains any alphabet ,which is not my requirement.
I have gone through the discussions but couldn't find what i was looking for.Suggestions please!!
Try this
Make a macro
#define ACCEPTABLE_CHARECTERS #"0123456789."
And use it
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField==textFieldAmount)
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
return YES;
}
Check Your textfield containing only numbers or not by using below code :
BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [yourTextFieldText isSupersetOfSet:inStringSet];
if (!valid)
{
// Not numeric
}
else
{
//valid number
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:#""];
textField.text = filtered;
return NO;
}

Getting an IndexOutofBoundsException when implementing delegate method shouldChangeCharactersInRange in iOS

I have a UITextField in my application that I want to function like a calculator. I need it to have the default value of 0.00, and as the user enters digits, the numbers move from right to left, replacing the zeroes in 0.00 one digit at a time, and the application should be smart enough to add commas (,) after every three digits. To do this, I am implementing the delegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {}
as follows:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([[string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]]
isEqualToString:#""])
return YES;
NSString *previousValue = [[[textField.text stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] stringByReplacingOccurrencesOfString:#"." withString:#""] stringByReplacingOccurrencesOfString:#"," withString:#""];
string = [string stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
NSString *modifiedValue = [NSString stringWithFormat:#"%#%#",previousValue,string];
modifiedValue = [NSString stringWithFormat:#"%#.%#",[modifiedValue substringToIndex:modifiedValue.length-2],[modifiedValue substringFromIndex:modifiedValue.length-2]];//this is the line that is causing the error
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
modifiedValue = [formatter stringFromNumber:[NSNumber numberWithFloat:[modifiedValue floatValue]]];
textField.text = modifiedValue;
return NO;
}
However, I am getting the following error:
'NSRangeException', reason: '*** -[__NSCFString substringToIndex:]: Range or index out of bounds'
This error was thrown the moment I tried to enter a number in the textfield. Can anyone see what I am doing wrong?
Thanks in advance to all who reply.
Yeah, this bit right here:
[modifiedValue substringToIndex:modifiedValue.length-2]
seems to assume that the length of the string is at least 2.
Which is probably isn't, at least when the user is typing his/her first character into an empty text field.
How about putting a length check around the whole thing, only doing the guts of the "shouldChangeCharactersInRange" method if the length is greater than two characters?

Resources