3

I have a TextField in xCode and someone ask me to admit just certain types of characters giving me this text string:

^([A-ZÑÑÁÉÍÓÚÀÈÌÒÙÄËÏÖÜ ])*$

or this one:

^([0-9])*$

I Know a method using UITextFieldDelegate named textField shouldChangeCharactersInRange and this is the way I implement this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *allowedCharacters  = @"abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMÑNOPQRSTUVWXYZ0123456789.@-_ ";
    NSCharacterSet *characterSet    = [NSCharacterSet characterSetWithCharactersInString:allowedCharacters];


    if ([string stringByTrimmingCharactersInSet:characterSet].length == 0)textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return NO;

    return YES;


}

if you see, on my programming my variable allowedCharacters stores all my valid characters but is in a different format (I have to write all the allowed characters),

I want to program something similar but with my partner's text format ^([0-9])*$ (text using ranges) how do I do that

Thanks in advance

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jesús Ayala
  • 2,743
  • 3
  • 32
  • 48

1 Answers1

3

you can use this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Valida el patron que se introduce en el campo de texto
    if (![self validateString:string withPattern:@"^([A-Z0-9.@-_ ])*$"])    return NO;

    return YES;
}

in the withPattern parameter insert your regex expression, and then here it is the method which does all the magic:

- (BOOL)validateString:(NSString *)string withPattern:(NSString *)pattern
{
    NSError *error              = nil;
    NSRegularExpression *regex  = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSAssert(regex, @"Unable to create regular expression");

    NSRange textRange   = NSMakeRange(0, string.length);
    NSRange matchRange  = [regex rangeOfFirstMatchInString:string options:NSMatchingReportProgress range:textRange];

    BOOL didValidate    = NO;

    // Did we find a matching range
    if (matchRange.location != NSNotFound)  didValidate = YES;

    return didValidate;
}

test it and tell us how did it go

Jesus
  • 8,456
  • 4
  • 28
  • 40