Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

monkeyblue

macrumors newbie
Original poster
Jan 20, 2011
2
0
Hi,

I have been trying to figure out how to restrict a users input with NSTextField so that it only allows numeric input with a single decimal point however for the past few hours all my efforts have failed.

So far I have created a custom numberformatter and assigned it to the NSTextfield in interface builder and now I can restrict the length of the input and also what is allowed to be inputted by using the following:

Code:
-(bool)isPartialStringValid:(NSString *)partialString 
           newEditingString:(NSString**)newString 
           errorDescription:(NSString**)error 
{ 
	
	NSRange inRange;
	NSCharacterSet *allowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
	inRange = [partialString rangeOfCharacterFromSet:allowedChars];
	
	NSLog(@"Original String = %@", partialString);
	if(inRange.location != NSNotFound)
	{
		NSLog(@"Name input contains disallowed character.");
		NSBeep();
		return NO;
	}
	
	*newString = partialString;
	return YES; 
}

This works fine however the user can input more than one decimal i.e. 12...23..22, I am unsure of how to restrict this, any help would be appreciated.

Thanks Aaron
 
Hi,

After a good nights sleep I have managed to solve this, its possibly not the best code in the world but it now works in my application and restricts the input to numeric with a single decimal place:

Code:
- (BOOL)isPartialStringValid:(NSString **)partialStringPtr
	   proposedSelectedRange:(NSRangePointer)proposedSelRangePtr
			  originalString:(NSString *)origString
	   originalSelectedRange:(NSRange)origSelRange
			errorDescription:(NSString **)error {

	int total;
	NSRange inRange;
	NSCharacterSet *allowedChars;

	// Check Original String for Decimal
	NSArray * array = [*partialStringPtr componentsSeparatedByString:@"."];
	total = [array count] -1;
	
	if (total > 1) {
		// Decimal place already exists
		allowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
	} else {
		allowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
	}
	
	inRange = [*partialStringPtr rangeOfCharacterFromSet:allowedChars];
	if(inRange.location != NSNotFound)
	{
		NSLog(@"Name input contains disallowed character.");
		NSBeep();
		return NO;
	} else {
		return YES;
	}
}

Thanks Aaron
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.