// BWNumberOnlyFormatter.m -- restrict typed in numbers to only digits

// Copyright (C) 2003 Borkware
// We use the BSD License.  Check out http://borkware.com/license

#import "BWNumberOnlyFormatter.h"

// Partially taken from Bill Cheeseman's Vermont Recipes.  
// Buy the book.  It's great

@implementation BWNumberOnlyFormatter

- (BOOL) isPartialStringValid: (NSString **) partialStringPtr
	proposedSelectedRange: (NSRange *) proposedSelRangePtr
	       originalString: (NSString *) origString
	originalSelectedRange: (NSRange) origSelRange
	     errorDescription: (NSString **) errorPtr
{
    int result = NO; // default to not valid

    // take the complement of the set of digits.  This lets us
    // use NSString's rangeOfCharacterFromSet as one-liner
    // to see if there are any Bad (non-digit) characters in
    // there
    NSCharacterSet *nonDigits;
    nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

    // just look at stuff that was added, whether by keystroke,
    // a paste, or a drag-and-drop
    NSRange newStuff;
    newStuff = NSMakeRange (origSelRange.location,
			    proposedSelRangePtr->location
			    - origSelRange.location);

    // extract the new text
    NSString *newStuffString;
    newStuffString = [*partialStringPtr substringWithRange: newStuff];

    // finally see if the new text has any non-digits in it
    if ([newStuffString rangeOfCharacterFromSet: nonDigits
			options: NSLiteralSearch].location != NSNotFound) {
        *errorPtr = NSLocalizedString (@"Input is not an integer",
				       @"number formatter input not an integer error");
    } else {
        *errorPtr = nil;
	result = YES;
    }

    return (result);

} // isPartialStringValid


@end // BWNumberOnlyFormatter


/* $Id: BWNumberOnlyFormatter.m,v 1.5 2003/01/03 21:16:57 markd Exp $ */

