how to restrict special characters in UITextField in iPad? - objective-c

In my iPad app. I have one UITextField. User would enter some value in that text field. This value has to be Alpha Numeric. I want to show an alert to the user if he/she enters any special character.
How can I do it? What should be the condition for alert?
Any help would be highly appreciated.
Thanks and regards,
PC

Implement textField:shouldChangeCharactersInRange:replacementString: in the delegate, check the replacement string for special characters, and disallow the replacement if you detect any.
The easiest way to check for non-alphanumerics is as follows:
if ([replacementString rangeOfCharacterFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]].location != NSNotFound) {
// There are non-alphanumeric characters in the replacement string
}

You can do it as :-
#define ACCEPTABLE_CHARECTERS #" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];
if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1)
return NO;
else
return YES;
}

Related

How to find a particular text in UITextField?

In my iPhone app I have a UITextField ans text field value is being taken into an NSString, I want to find if a particular character " is typed in that
How can I do that?
UITextField *textField;
NSString *String=textField.text;
-(IBAction)FindCharecter:(id)sender
{
// if String Contain ",then i wish to print #"Found symbol"
}
UITextField *textField;
NSString *string=textField.text;
if ([string rangeOfString:#"\""].location == NSNotFound) {
NSLog(#"string does not \"");
} else {
NSLog(#"string contains \"");
}
check this
Try This:
-(IBAction)FindCharecter:(id)sender
{
// if String Contain ",then i wish to print #"Found symbol"
if ([String rangeOfString:#"\""].location != NSNotFound) {
NSLog(#"Found");
}
else{
NSLog(#"Not Found");
}
}
Implement the following delegate of UITextField
-(NSString *)ValidateSearchString:(NSString *) aString{
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"YourString"] invertedSet];
if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
return #"Not Found";
}
return #"Found";;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog("particular character %#",[self ValidateSearchString:string]);
// string will contain the particular character typed;
return YES;
}
You need to confirm and implement UITextFieldDelegate protocol.
1) If you want to check for a pattern on the go (when user typing itself), you need to implement
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
2) If you want to check when user completed typing, you may want to implement
- (void)textFieldDidEndEditing:(UITextField *)textField
Now to do the actual comparison process
if([textFieldString rangeOfString:#"YOUR_COMPARISON_STRING"].location == NSNotFound){
//your pattern is not typed yet
}else{
//There it is..
}
You can use shouldChangeCharactersInRange delegate method for this.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#"\""])
{
NSLog(#"Entered \" ");
}
}
Or you can use: rangeOfString of NSString class.
if ([textField.text rangeOfString:#"\""].location == NSNotFound)
{
NSLog(#"Entered \" ");
}
For reference:
textField:shouldChangeCharactersInRange:replacementString:
Asks the delegate if the specified text should be changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Parameters
textField
The text field containing the text.
range
The range of characters to be replaced
string
The replacement string.
Return Value
YES if the specified text range should be replaced; otherwise, NO to
keep the old text. Discussion
The text field calls this method whenever the user types a new
character in the text field or deletes an existing character.
Availability
Available in iOS 2.0 and later.
UITextFieldDelegate
rangeOfString:
Finds and returns the range of the first occurrence of a given string
within the receiver.
- (NSRange)rangeOfString:(NSString *)aString
Parameters
aString
The string to search for. This value must not be nil.
Important: Raises an NSInvalidArgumentException if aString is nil.
Return Value
An NSRange structure giving the location and length in the receiver of
the first occurrence of aString. Returns {NSNotFound, 0} if aString is
not found or is empty (#"").
Discussion
Invokes rangeOfString:options: with no options.
This method detects all invalid ranges (including those with negative
lengths). For applications linked against OS X v10.6 and later, this
error causes an exception; for applications linked against earlier
releases, this error causes a warning, which is displayed just once
per application execution. Availability
Declared In NSString.h
Declared In UITextField.h
NSString Class

How to set max string length for UIAlertView text field

How can I set the max string length for a textfield created within a UIAlertView? I am using Xcode 4.5 and building the app on 10.8 (OS X) Currently I have UIAlertView that launches when the user clicks a button. The user will scan their RFID badge, and I want the input textfield of the UIAlertView to be limited to 10 (ten) characters so the user can't fudge association process.
You can check the length of the text in the delegate method of the textField:
textField:shouldChangeCharactersInRange:replacementString:
And return NO if you don't want to change.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length - range.length + string.length > 10) {
return NO;
}
return YES;
}
Looks like the above answer is almost right.
When typing single characters, range.length (for this method) appears to always be zero, while the location increments.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(#"Range: %#", NSStringFromRange(range));
return ( range.location < 10 );
}
edit: length would probably be longer if you doing something other than single-character typing, i.e. pasting a line, etc.

Character limit for multiple uitextfields

I'm a fairly new programmer and am having trouble with some UITextfields, basically i have two text fields and i want to limit the amount of characters in one of them to a certain amount, whilst allowing the other field to have lots.
I found a post that recommended this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [[textField text] length] + [string length] - range.length;
return (newLength > 2) ? NO : YES;
}
However that seems to affect both text fields. I'm not sure how to target one field.
Can anyone help, also one thing, i get whats going on in that code up until - range. length, is the range the total amount of characters?
Ok so the issue here is that the object which contains this code is the delegate to both textfields. Two ways to solve it. Either dont add the textfield you dont care about the length of as a delegate or the better way would be to differentiate between the fields during the shouldChangeCharactersInRange method.
For the second part of your question- range is the character(s) that is/are being changed in the text field and consists of: The position of the string to change, the length of the string being changed.
My personal preference is to say if the text length is greater than max length and your not deleting then refuse the change.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(textField == self.textfieldYouWantToLimitTheLengthOf){
if(textField.text.length > 2 && ![string isEqualToString:#""]){
return NO;
}
}
return YES;
}

Knowing the complete changed string in textField:shouldChangeCharactersInRange:replacementString:

I just asked a question about how to monitor changes to a UITextField and received this response :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacementStr {
// Enable "Next" if you like what's entered in the replacementStr
}
This works, but the replacement string is not the whole string, just what it is adding. How can I get the whole string? My objective is to see if the string in the text field is blank or equal to a certain number (in different scenarios).
Please note that the outlet to the text field doesn't work in this case, because this method is being called before the text in the field changes.
NSString * proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:replacementString];
Swift Version
In Swift We need to cast textField's text to NSString. The following can be useful:
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
// [textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
NSLog(#"%#",searchStr);
return YES;
}

Limit text field length

Please tell me how I can set the range of a text field to a maximum of six and minimum of one.
Set self as textfield's delegate and implement this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (newString.length < 1) {
// too short
} else if (newString.length > 6) {
// too long
}
return YES;
}
I'd suggest you to have a UILabel that will say in red text that text is too short or too long. Just preventing user from typing into textfield when they reach 6 chars or deleting last character when they change their mind is a very bad user experience.
Implement the delegate method textField:shouldReplaceCharactersInRange:replacementString: and have your implementation return NO if the resulting string would fall outside of your constraints.