How to verify UITextField text? - iphone

I need to make sure that the user is only entering numbers into my textfield. I have the keyboard set to numbers, but if the user is using an external keyboard they might enter a letter. How can I detect if any characters in my textfield.text are characters instead of numbers?
Thanks!

You can choose what characters can input into the textField
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
/* this ensures that ONLY numbers can be entered, no matter what kind of keyboard is used */
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
return NO;
}
}
/* this allows you to choose how many characters can be used in the textField */
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 7) ? NO : YES;
}

Whenever the user enters a key this textfield delegate will be called.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Inside this check whether the text contains characters. if it is do your action. like promptimg a alert or something.

Implement textField:shouldChangeCharactersInRange:replacementString: in the text field's delegate and return NO if the passed string contains invalid characters.

Related

How to check that any of the textfields inputed values is not number and is negative then show message

I have many textField Inputs for the calculations I want that if any of the inputs is not a number and negative number then it show error message on button click and not to move to the other screen
There's at least a couple ways you can handle this, James.
#1) specify numeric keyboards for those specific numeric-only text fields in the storyboard / xib file
#2) set a delegate for the text field and when the user is done editing (e.g. textFieldDidEndEditing:), look at the contents of the text field and if you see anything that isn't a number, throw up a UIAlert.
One way to do this would be:
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSRange rangeOfInvalidCharacter = [textField.text rangeOfCharacterFromSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
if(rangeOfInvalidCharacter.location != NSNotFound)
{
// throw up a UIAlert here
// and, if you want, erase the bogus text via:
textField.text = #"";
return;
}
// and if we get here, that means the text field contents are only digits.
}
Try this code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
{
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
return NO; // For don't add this character
}
return YES; // For input a true character
}

shouldChangeCharactersInRange taking only one digit at time

i am trying to get total value after multiplying price and quantity in to text field. I not getting value when quantity is 10 or having any two or three digits.This method takes only one character at time.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
if(textField == quantityText)
{
NSCharacterSet *charactersToRemove =[[ NSCharacterSet alphanumericCharacterSet ]
invertedSet];
NSRange inRange=[string rangeOfCharacterFromSet:charactersToRemove];
if(inRange.location != NSNotFound)
{
quantityText.text =[ quantityText.text
stringByTrimmingCharactersInSet:charactersToRemove ];
return NO;
}
if ([textField text] )
{
float quantity = [string floatValue];
float price = [[priceLabel text] floatValue];
float h = quantity * price;
amountText.text=[NSString stringWithFormat:#"%f",h];
}
else
{
return NO;
}
}
return YES;
}
You're only using the replacementString value for your calculation, which is the last character that was typed, not the whole the whole string.
So if I type '1' then function uses 1 as the value, then if I type '0' to make 10, your function only uses the '0' as the value.
You need to get the whole text of the quantityText textfield and use that. You could get that by taking textField.text and then replacing the specified range with the replacementString.
To be honest though it's a lot easier just to register for the UITextFieldTextDidChangeNotification instead of using the textfield:shouldChangeCharactersInRange:replacementString: method.
See this answer for details.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
this delegate method is called whenever user types a new character in to the textfield and the string object will contain only the last typed character. so instead of using (NSString *)string use textField.text

textfield inputs range in interface builder

I have multiple textfields in my nib file.
I want to decide the input range in my one textfield to 6-16 digits and I don't want to change any other textfield input. For that I made a method called tflimit as below.
-(IBAction)tflimit:(id)sender
{
if([textfields1.text length]>=15 )
{
[textfields1 resignFirstResponder];
}
}
With this method I can input only 16 digits input.
How can I decide the range(6-16) of an input in the textfield without changing other codes.
You can filter user input in textField:shouldChangeCharactersInRange:replacementString: method in text field delegate:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == textfields1){// Apply logic only to required field
NSString* newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return [newString length] < 16 && [newString length] > 5;
}
return YES;
}
Note that to work correctly this method require textfield to be pre-populated with text at least 5 characters long.

Solution for iPhone new file dialog keyboard

i want to let the user type in the name of a new file, so there are certain characters i want to prevent entry on. is there a special keyboard i can use or can i disable certain keys on the iphones keyboard.
is the answer to just run a regular expression on the input text and tell the user the filename is invalid (if so what would that regular expression be?)
ANSWER: (or what i ended up doing)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
BOOL valid;
//if the user has put in a space at the beginning
if ([string isEqualToString:#" "]){
if (range.location == 0){
valid = NO;
}
else{
valid = YES;
}
}
//otherwise test for alpha numeric
else{
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
valid = [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:#""];
}
//print the warning label
if (valid == NO){
[errorLabel setText:#"Invalid input"];
}
else{
[errorLabel setText:nil];
}
return valid;
}
You can implement the delegate method
For UITextField,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
For UITextview
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
and decide weather to append the entered characters or not.
You can implement the UITextFieldDelegate protocol and use textField:shouldChangeCharactersInRange:replacementString: to watch the text entry and prevent unwanted characters by returning NO.

Filtering characters entered into a UITextField

I have a UITextField in my application. I'd like to restrict the set of characters that can be can be entered into the field to a set that I have defined. I could filter the characters entered into the field when the text is committed using the UITextFieldDelegate method:
- (BOOL)textFieldShouldReturn:(UITextField*)textField
However, this gives the user a false impression as although restricted characters are removed from the final value, they were still visibly entered into the text field before pressing Return/Done/etc. What is the best approach that would prevent restricted characters appearing in the text field as they are selected on the keyboard?
Note: I am operating under the assumption that I have little control over which keys are provided by the iPhone keyboard(s). I am aware that I can switch between various keyboard implementations but am under the impression that I can't disable specific keys. This assumption may be incorrect.
I did as marcc suggested and it worked well. Sample implementation follows.
Note: Variable names were selected for brevity and do not reflect my coding standards:
...
myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"xyzXYZ"];
...
}
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered {
for (int i = 0; i < [textEntered length]; i++) {
unichar c = [textEntered characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
return NO;
}
}
return YES;
}
Look at textField:shouldChangeCharactersInRange
This method is called by the UITextFieldDelegate whenever new characters are typed or existing characters are deleted from the text field. You could return NO to not allow the change.
Here is one of the cleanest approaches to restricting characters entered in a UITextField. This approach allows the use of multiple predefined NSCharacterSets.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacters formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
[allowedCharacters formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){
return YES;
}
return NO;
}
Look at the UITextViewDelegate method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string.
It's exactly what you need.
This is what I use to restrict the user to uppercase A-Z. Adjust the regex variable according to taste:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* regex = #"[^A-Z]";
return ([string rangeOfString: regex
options:NSRegularExpressionSearch].location == NSNotFound);
};
How about this?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* regex = #"[^a-z]";
return ([[string lowercaseString] rangeOfString: regex
options:NSRegularExpressionSearch].location == NSNotFound);
};
Note:
I am making all characters to lower case [string lowercaseString] so that you don't need to write in regex for captial/small letters.
You could loop and keep checking if the UITextField.text property has changed once the DidBeginEditing method gets called. If it has, check the text and remove an bad characters.