UITextField NSString length problems while formatting NSString - iphone

I have been working on this for a few days now and I have some buzzy things going on with my textfields... and it's got to the point where I need to take a step back and hope someone with a fresh pair of eyes can shed light on the situation.
basically what I'm doing is formatting a 20 character string into sets of 5 as the user types after every 5th character a hyphen pops into the string, that works sweet.
I have a submit button that is not perusable until the 20th character is entered, this also works but where it gets CRAZY! is if you delete back one character the submit button still works.. then you delete back one more character and it doesn't work... I'm at a loss as my if statements conditions don't work like they should I specify == 23 characters and you have to hit one of the keys 24 times to get into that statement.. it makes no logical sense.
anyway if you could help me with the first question that would be great then if you have any ideas on the second question that would be great.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *separator = #"-";
int seperatorInterval = 5; //how many chars between each hyphen
NSString *originalString = [regTextField.text stringByReplacingOccurrencesOfString:separator withString:#""];
if (textField.text.length == 23 && range.length == 0){
return NO; // return NO to not change text
}
if (![originalString isEqualToString:#""] && ![string isEqualToString:#""]) {
NSString *lastChar = [regTextField.text substringFromIndex:[regTextField.text length] - 1];
int modulus = [originalString length] % seperatorInterval;
if (![lastChar isEqualToString:separator] && modulus == 0) {
regTextField.text = [regTextField.text stringByAppendingString:separator];
}
}
[self validateTextFields];
return YES; //Keep accepting input from the user
}
//Validating text field to see if Submit button can be pressed or not
-(IBAction) validateTextFields {
NSString *intString = [NSString stringWithFormat:#"%d", regTextField.text.length];
NSLog(#"Starting %#", intString);
if (regTextField.text.length < 22){
[submitButton setEnabled:NO]; //enables submitButton
}
else {
regTextField.text = [regTextField.text substringToIndex:22];
[submitButton setEnabled:YES]; //disables submitButton
}
intString = [NSString stringWithFormat:#"%d", regTextField.text.length];
NSLog(#"Done %#", intString);
}

You need to add = sign in this if statement
if (regTextField.text.length <= 22){
or just change the number to 23 either way it should work
if (regTextField.text.length < 23){

Related

How to Append a Special Character after every 3 characters in UITextField Ex: (123-12346) like '-' i did it but issue while Clear

I am getting Phone card number form user in UI text field. The format of number is like
123-4567-890
I want that as user types 123 automatically - is inserted in UITextField same after 4567 - and so on.
I Did it using following code in UITextField delegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
NSLog(#"***** %d",textField.text.length);
if(textField.text.length == 3)
{
textField.text = [textField.text stringByAppendingString:#"-"];
}
return YES;
}
But the Problem raised while clear the text, When we start clearing.
Last 3 digits 890 clears and then - addded, we cleared it and again added and soooo on so clearing stop at
We clear all the text at a time using
textField.clearButtonMode = UITextFieldViewModeWhileEditing; //To clear all text at a time
But our requirement is user must delete one character at a time.
How to achieve it?
During clearing replacementString should be empty #"". So replacement string should be checked also in addition to length check. Like this:
if (textField.text.length == 3 && ![string isEqualToString:#""]) {
// append -
}
USE: I have seen this somewhere in this forum, It worked for me
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *filter = #"###-####-###";
if(!filter) return YES;
NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(range.length == 1 && string.length < range.length && [[textField.text substringWithRange:range] rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:#"0123456789"]].location == NSNotFound)
{
NSInteger location = changedString.length-1;
if(location > 0)
{
for(; location > 0; location--)
{
if(isdigit([changedString characterAtIndex:location]))
break;
}
changedString = [changedString substringToIndex:location];
}
}
textField.text = filteredStringFromStringWithFilter(changedString, filter);
return NO;
}
NSString *filteredStringFromStringWithFilter(NSString *string, NSString *filter)
{
NSUInteger onOriginal = 0, onFilter = 0, onOutput = 0;
char outputString[([filter length])];
BOOL done = NO;
while(onFilter < [filter length] && !done)
{
char filterChar = [filter characterAtIndex:onFilter];
char originalChar = onOriginal >= string.length ? '\0' : [string characterAtIndex:onOriginal];
switch (filterChar) {
case '#':
if(originalChar=='\0')
{
done = YES;
break;
}
if(isdigit(originalChar))
{
outputString[onOutput] = originalChar;
onOriginal++;
onFilter++;
onOutput++;
}
else
{
onOriginal++;
}
break;
default:
outputString[onOutput] = filterChar;
onOutput++;
onFilter++;
if(originalChar == filterChar)
onOriginal++;
break;
}
}
outputString[onOutput] = '\0';
return [NSString stringWithUTF8String:outputString];
}

How to check if a UITextfield has Text in it?

I just followed a tut on making a conversion app. It was good, but I wanted to expand on it. The tut has you input a value in for Fahrenheit and then converts to Celsius. Pretty basic. So I wanted to add a Kelvin conversion as well. But the code only let you plug in a number for the Fahrenheit. So after adding the Kelvin text field, I wanted to check to see which text box had text in it. So I used the following code:
- (IBAction)convert:(id)sender
{
if ([fahrenheit isFirstResponder])
{
float x = [[fahrenheit text] floatValue];
float y = (x - 32.0f) * (5.0f/9.0f); //celcius
float z = y + 273.15f; //kelvin
[celcius setText:[NSString stringWithFormat:#"%3.2f" , y]];
[kelvin setText:[NSString stringWithFormat:#"%3.2f" , z]];
[fahrenheit resignFirstResponder];
} else if ([celcius isFirstResponder])
{
float x = [[celcius text] floatValue];
float y = 32.0f + ((9.0f/5.0f) * x); //farenheit
float z = x + 273.12f; //kelvin
[fahrenheit setText:[NSString stringWithFormat:#"%3.2f" , y]];
[kelvin setText:[NSString stringWithFormat:#"%3.2f" , z]];
[celcius resignFirstResponder];
}else if ([kelvin isFirstResponder])
{
float x = [[kelvin text] floatValue];
float y = x - 273.15f; //celcius
float z = 32.0f + ((9.0f/5.0f) * y); //farenheit
[celcius setText:[NSString stringWithFormat:#"%3.2f" , y]];
[fahrenheit setText:[NSString stringWithFormat:#"%3.2f" , z]];
[kelvin resignFirstResponder];
}
}
This allowed me to input a number in any text field and then convert. But then I decided to dismiss the keyboard. My code said to resignFirstResponder. But then the convert action did not work because now there was no first responder. Any clues as to how I can check which text box has text in it, and then do the conversions? Thanks in advance for any help.
if( [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] != nil && [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] != #"" )
{
// text field has text
// get text without white space
NSString * textWithoutWhiteSpace = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
This is for checking textView is empty or not:-
if([textView.text isEqualToString:#""])
{
//textView is Empty
}
else
{
//textView has text
}
If you want to check it for white space as well, first remove white spaces from string then check ... like this -
NSString *trimmedString = [tV.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([trimmedString isEqualToString:#""])
{
NSLog(#"textView is empty");
}
else
{
NSLog(#"textView has some value");
}
Just use the hasText method.
Example:
if(_yourTextField.hasText)
{
// Do something.
}
if(textView.text.length > 0)
{
//text present
}
else
{
//no text
}
Better solution is make all conversions on the fly, add new action to all textFields
[textField addTarget:self action:#selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
Then in method textChanged: do something like this:
- (void) textChanged:(UITextField *)tf {
if (tf.text.floatValue > 0) {
if (tf == fahrenheit) {
//Do convertion for fahrenheit
}
.
.
.
//etc.
}
}
On response to Meno's answer
DO NOT USE != #""
this check for pointer equality vs String equality
use:
[string isEqualToString:#""];
If you want to know it DURING input, and probably performs actions based on this info, you shall use:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
There were a few problems in some of the other answers, like they didn't use isEqualToString, and they superfluously removed potential characters from a string that we are only interested in if it is nil or not.
I don't have enough reputation to comment, so I am posting this as an answer.
For a similar issue, I used this to check each textfield that I needed to check for being empty:
- (BOOL) isEmpty:(UITextField*) field
{
if (!(field.text) ||
([[field.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString: #""]))
{
return YES;
}
else
{
return NO;
}
}
If you need an NSString with white space removed:
NSString *nonWhiteSpaceString = [textfield.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Then you could use the length as a boolean:
BOOL textFieldHasText = nonWhiteSpaceString.length;

Decimal style improvement objective c calculator

I'm doing the calculator tutorial for iOS and I've done some research for doing the decimal style. So far on my research, I've gone through this code below
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = sender.currentTitle;
NSString *decimal = #".";
BOOL decimalAlreadyEntered = [self.display.text rangeOfString:decimal].location == NSNotFound ? NO : YES;
if (self.userIsInTheMiddleOfEnteringANumber) {
if (([digit isEqual:decimal] && !decimalAlreadyEntered) || !([digit isEqual:decimal])) {
[self.display setText:[[self.display text] stringByAppendingString:digit]];
}
}
else if ([self.display.text isEqual:#"0"] && digit == decimal){
[self.display setText:[[self.display text] stringByAppendingString:digit]];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
else {
[self.display setText:digit];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
This code helped me to prevent multiple decimal points being pressed by the user, and limit it only to one (as in 2.09). Cool! However during the start of the app, when I press on the decimal point and pressed on a number, say 1, the label will only display ( .1) instead of (0.1) . Any help for the improvement is much appreciated :)
In - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string you can check whether first value is "." then replace text value by "0.", whatever user has entered.And perform this check only when textfield value is ".something".
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
if (range.location == 0 && [string isEqualToString:symbol]) {
// decimalseparator is first
textField.text = [NSString stringWithFormat:#"0%#",textField.text];
return YES;
}
}

Numberpad backspace not updating textField.text.length

I'm currently formatting my a textfield in xcode, every 5th character I add a hyphen.
However I'm having alot of trouble I am currently wanting to check my textfields.text.length then once the length reaches 23 characters the submit button is press-able. So far this works where I have trouble is say if the user enters 23 characters and the button is press-able if the user decided to go back and delete one character there is nothing to update the new text length as I don't know how to catch the delete button of the numberpad... Dose anyone know how to do this?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *separator = #"-";
int seperatorInterval = 5;
NSString *originalString = [regTextField.text stringByReplacingOccurrencesOfString:separator withString:#""];
if (![originalString isEqualToString:#""] && ![string isEqualToString:#""]) {
NSString *lastChar = [regTextField.text substringFromIndex:[regTextField.text length] - 1];
int modulus = [originalString length] % seperatorInterval;
[self validateTextFields];
if (![lastChar isEqualToString:separator] && modulus == 0) {
regTextField.text = [regTextField.text stringByAppendingString:separator];
}
}
[self validateTextFields];
return YES;
}
-(IBAction) validateTextFields {
if (regTextField.text.length >= 22){
[submitButton setEnabled:YES]; //enables submitButton
}
else {
[submitButton setEnabled:NO]; //disables submitButton
}
}
Try something like this:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// Any new character added is passed in as the "text" parameter
if (!([text isEqualToString:#""] && range.length == 1) && [textView.text length] >=140 ) {
return NO;
}
// For any other character return TRUE so that the text gets added to the view
return YES;
}
Where the block:
([text isEqualToString:#""] && range.length == 1)
Is the check for the backspace.
Capturing the backspace on the Number Pad Keyboard

What's the best way to validate currency input in UITextField?

My application allows the user to enter a numeric value (currency) in a UITextField control, but the keyboard layout that I wish was available is unfortunately not one of the built-in options, so I had to choose the "Numbers & Punctuation" option in Interface Builder. Here's the corresponding dialog window in IB:
So when my application asks the user for the input, it is displaying the following:
Which is perfectly fine, but look at all of the extra keys available to the user! One could easily enter "12;56!" in the text field, and I assume I have to validate that somehow.
So my question is: how do I validate currency values entered into a UITextField?
I have the urge to answer because this was the first entry I saw when I googled and the highest ranked answer wouldn't allow me to enter a currency.
I'm german, and in germany (and in many other countries) we use , as the decimalseparator.
I just wrote a similar method and this is what I have right now.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
static NSString *numbers = #"0123456789";
static NSString *numbersPeriod = #"01234567890.";
static NSString *numbersComma = #"0123456789,";
//NSLog(#"%d %d %#", range.location, range.length, string);
if (range.length > 0 && [string length] == 0) {
// enable delete
return YES;
}
NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
if (range.location == 0 && [string isEqualToString:symbol]) {
// decimalseparator should not be first
return NO;
}
NSCharacterSet *characterSet;
NSRange separatorRange = [textField.text rangeOfString:symbol];
if (separatorRange.location == NSNotFound) {
if ([symbol isEqualToString:#"."]) {
characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersPeriod] invertedSet];
}
else {
characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersComma] invertedSet];
}
}
else {
// allow 2 characters after the decimal separator
if (range.location > (separatorRange.location + 2)) {
return NO;
}
characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbers] invertedSet];
}
return ([[string stringByTrimmingCharactersInSet:characterSet] length] > 0);
}
While you can putz around in the NSNumberFormatter, I found it easier to just screen out anything but 0-9 and .
This is working well for me:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}
I found this to be a relatively clean approach. I haven't tested it with non-US currencies but since it uses the NSNumberFormatter's properties I believe it should handle them correctly.
Start by setting up a formatter some place:
formatter = [NSNumberFormatter new];
[formatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[formatter setLenient:YES];
[formatter setGeneratesDecimalNumbers:YES];
Use the formatter to parse and reformat their input. It also handles shifting the number when digits are added and removed.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *replaced = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSDecimalNumber *amount = (NSDecimalNumber*) [formatter numberFromString:replaced];
if (amount == nil) {
// Something screwed up the parsing. Probably an alpha character.
return NO;
}
// If the field is empty (the initial case) the number should be shifted to
// start in the right most decimal place.
short powerOf10 = 0;
if ([textField.text isEqualToString:#""]) {
powerOf10 = -formatter.maximumFractionDigits;
}
// If the edit point is to the right of the decimal point we need to do
// some shifting.
else if (range.location + formatter.maximumFractionDigits >= textField.text.length) {
// If there's a range of text selected, it'll delete part of the number
// so shift it back to the right.
if (range.length) {
powerOf10 = -range.length;
}
// Otherwise they're adding this many characters so shift left.
else {
powerOf10 = [string length];
}
}
amount = [amount decimalNumberByMultiplyingByPowerOf10:powerOf10];
// Replace the value and then cancel this change.
textField.text = [formatter stringFromNumber:amount];
return NO;
}
Perhaps you could attach a UITextFieldDelegate on the control and have it implement textField:shouldChangeCharactersInRange:replacementString: That way, if it sees any characters that you don't want in the field, it can reject them.
In conjunction with the textField:shouldChangeCharactersInRange:replacementString: suggestion made by Marc, you should pass the text through an NSNumberFormatter using an NSNumberFormatterCurrencyStyle. This will handle the quirks of currency formatting and handle locale specific options.
There's a "Data Formatting Programming Guide for Cocoa" section in the iPhone documentation if you search for it. Sadly, most of the UI information here is Mac OS X specific (doesnt work on iPhone) but it'll show you how to use the formatter classes.
I found that the shouldChangeCharactersInRange screws up the pop-up keyboard, backspace and "Done" button as well. I found if I handled 0 length strings and allowed control characters though, it worked fine.
I don't like using NSNumberFormatter because it insists that the number is well-formed at all stages while the user is editing and that can be infuriating if you, say, want to have two decimal points in the number for a moment until you delete the one that's in the wrong spot.
Here's the code I used:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string length] < 1) // non-visible characters are okay
return YES;
if ([string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]].length == 0)
return YES;
return ([string stringByTrimmingCharactersInSet:[self.characterSet invertedSet]].length > 0);
}
Where self.characterSet holds the characters that are acceptable, I used this method to create it for a currency:
- (NSCharacterSet *)createCurrencyCharacterSet
{
NSLocale *locale = [NSLocale currentLocale];
NSMutableCharacterSet *currencySet = [NSMutableCharacterSet decimalDigitCharacterSet];
[currencySet addCharactersInString:#"-"]; // negative symbol, can't find a localised version
[currencySet addCharactersInString:[locale objectForKey:NSLocaleCurrencySymbol]];
[currencySet addCharactersInString:[locale objectForKey:NSLocaleGroupingSeparator]];
[currencySet addCharactersInString:[locale objectForKey:NSLocaleDecimalSeparator]];
return [[currencySet copy] autorelease];
}
The somewhat unhappy code [[currencySet copy] autorelease] returns an immutable NSCharacterSet.
Using [NSCharacterSet decimalDigitCharacterSet] also includes the Indic and Arabic equivalent characters which hopefully means that people use those languages can use their alphabet's digits to enter numbers.
It's still necessary to check that NSNumberFormatter can parse the user's input and alert if it can't; nonetheless, it makes a nicer experience when only legit characters can be entered.
I keep seeing that people don't know how to properly determine the resulting string when implementing shouldChangeCharactersInRange.
Here's how you get the new text that would be entered if you returned YES:
NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
Once you have this new text, it's easy to check if that text is a valid number or not, and return YES or NO accordingly.
Keep in mind that all other solutions, such as those shown here, where one checks the length of "string", and such, may not work properly if the user tries to edit the string using a bluetooth keyboard with cursor keys or using the advanced editing features (select, cut, paste).
If you want them to only be able to enter numbers - you might also consider the number keypad
After finding a quick solution on stack overflow to handle US currency, I rewrote the function to safely handle international currencies as well. This solution will dynamically validate user input from a UITextField, correcting as they type.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMinimumFractionDigits:0];
// Grab the contents of the text field
NSString *text = [textField text];
// the appropriate decimalSeperator and currencySymbol for the current locale
// can be found with help of the
// NSNumberFormatter and NSLocale classes.
NSString *decimalSeperator = numberFormatter.decimalSeparator;
NSString *currencySymbol = numberFormatter.currencySymbol;
NSString *replacementText = [text stringByReplacingCharactersInRange:range withString:string];
NSMutableString *newReplacement = [[ NSMutableString alloc ] initWithString:replacementText];
// whenever a decimalSeperator or currencySymobol is entered, we'll just update the textField.
// whenever other chars are entered, we'll calculate the new number and update the textField accordingly.
// If the number can't be computed, we ignore the new input.
NSRange decimalRange = [text rangeOfString:decimalSeperator];
if ([string isEqualToString:decimalSeperator] == YES &&
[text rangeOfString:decimalSeperator].length == 0) {
[textField setText:newReplacement];
} else if([string isEqualToString:currencySymbol] == YES&&
[text rangeOfString:currencySymbol].length == 0) {
[textField setText:newReplacement];
} else if([newReplacement isEqualToString:currencySymbol] == YES) {
return YES;
}else {
NSString *currencyGroupingSeparator = numberFormatter.currencyGroupingSeparator;
[newReplacement replaceOccurrencesOfString:currencyGroupingSeparator withString:#"" options:NSBackwardsSearch range:NSMakeRange(0, [newReplacement length])];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *number = [numberFormatter numberFromString:newReplacement];
if([newReplacement length] == 1) {
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
number = [numberFormatter numberFromString:newReplacement];
}
if (number == nil) {
[newReplacement release];
return NO;
}
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
text = [numberFormatter stringFromNumber:number];
[textField setText:text];
}
[newReplacement release];
return NO; // we return NO because we have manually edited the textField contents.
}
Using an NSNumberFormatter is the correct answer. It will handle validation and converting the string to and from the correct object type.
You can also use Gamma-Point solution and evaluate if *aNumber is Nil, if its Nil, then it means a character that wasnt 0-9 . or , was entered, this way you can validate just numbers, it will nil the variable if any no-number char is entered.
I Couldn't find the appropriate implementation for currency validate. Here is my variant:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//if there is empty string return YES
if([proposedString length] == 0) {
return YES;
}
//create inverted set for appripriate symbols
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789.,"] invertedSet];
//if side symbols is trimmed by nonNumberSet - return NO
if([proposedString stringByTrimmingCharactersInSet:nonNumberSet].length != [proposedString length]) {
return NO;
}
//if there is more than 1 symbol of '.' or ',' return NO
if([[proposedString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#".,"]] count] > 2) {
return NO;
}
//finally check is ok, return YES
return YES;
}
Using shouldChangeCharactersInRange screws up the pop-up key board as the backspace button doesn't work.
Number formatter is the way to go. Here's a sample I used to find positive decimals. I call it during the validation check- for e.g. when the user clicks on the save button.
-(BOOL) isPositiveNumber: (NSString *) numberString {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *aNumber = [numberFormatter numberFromString:numberString];
[numberFormatter release];
if ([aNumber floatValue] > 0) {
NSLog( #"Found positive number %4.2f",[aNumber floatValue] );
return YES;
}
else {
return NO;
}
}