Skip to content

Instantly share code, notes, and snippets.

@densa
Created December 16, 2011 08:55
Show Gist options
  • Save densa/1485203 to your computer and use it in GitHub Desktop.
Save densa/1485203 to your computer and use it in GitHub Desktop.
Phone formatter
self.mask = @"111-222-3333";
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
if (textField.tag == 5)
{
//If the length of used entered text is equals to mask length the user input must be cancelled
if ([textField.text length] == [self.mask length]) {
if(! [string isEqualToString:@""])
return NO;
else
return YES;
}
//If the user has started typing text on UITextField the formatting method must be called
else if ([textField.text length] || range.location == 0)
{
if (string)
{
if(! [string isEqualToString:@""])
{
[self formatInput:textField string:string range:range];
return NO;
}
return YES;
}
return YES;
}
return NO;
}
else if (textField.tag == NAMEFIELD_TAG)
{
if ([textField.text length] >= MAXLENGTH)
{
textField.text = [textField.text substringToIndex:MAXLENGTH-1];
return NO;
}
return YES;
} else {
return YES;
}
}
//This method is responsible for add mask characters properly
- (void)formatInput:(UITextField*)aTextField string:(NSString*)aString range:(NSRange)aRange
{
//Copying the contents of UITextField to an variable to add new chars later
NSString* value = aTextField.text;
NSString* formattedValue = value;
//Make sure to retrieve the newly entered char on UITextField
aRange.length = 1;
NSString* _mask = [self.mask substringWithRange:aRange];
//Checking if there's a char mask at current position of cursor
if (_mask != nil) {
NSString *regex = @"[0-9]*";
NSPredicate *regextest = [NSPredicate
predicateWithFormat:@"SELF MATCHES %@", regex];
//Checking if the character at this position isn't a digit
if (! [regextest evaluateWithObject:_mask]) {
//If the character at current position is a special char this char must be appended to the user entered text
formattedValue = [formattedValue stringByAppendingString:_mask];
}
if (aRange.location + 1 < [self.mask length]) {
_mask = [self.mask substringWithRange:NSMakeRange(aRange.location + 1, 1)];
if([_mask isEqualToString:@" "])
formattedValue = [formattedValue stringByAppendingString:_mask];
}
}
//Adding the user entered character
formattedValue = [formattedValue stringByAppendingString:aString];
//Refreshing UITextField value
aTextField.text = formattedValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment