3

This simple validation method for NSString makes trouble. I have an NSString value and I want to validate the string, i.e, if the string contains only 'a to z' (or) 'A to Z' (or) '1 to 9' (or) '@,!,&' then the string is valid. If the string contains any other values then this the NSString is invalid, how can i validate this..?

As example:

Valid:

NSString *str="aHrt@2"; // something like this 

Invalid:

NSString *str="..gS$"; // Like this
Harish
  • 2,496
  • 4
  • 24
  • 48
  • 1
    Please note that the currently accepted answer allows for far more characters than desired including accented letters and letters from other alphabets. – rmaddy Jan 09 '13 at 16:07

9 Answers9

3

I would do something using stringByTrimmingCharactersInSet

Create an NSCharacterSet containing all valid characters, then trim those characters from the test string, if the string is now empty it is valid, if there are any characters left over, it is invalid

NSCharacterSet *validCharacters = [NSCharacterSet characterSetWithCharactersInString:@"myvalidchars"];
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:validCharachters];
BOOL valid = [trimmedString length] == 0;

Edit: If you want to control the characters that can be entered into a text field, use textField:shouldChangeCharactersInRange:replacementString: in UITextFieldDelegate

here the testString variable becomes the proposed string and you return YES if there are no invalid characters

wattson12
  • 11,176
  • 2
  • 32
  • 34
  • I'm getting input from UITextfield, where user allowed only to type characters like this 'a to z' (or) 'A to Z' (or) '1 to 9' (or) '@,!,&'. I have used Regex but no result...any sample code friends..? – Harish Jan 09 '13 at 08:57
3

Try using character sets:

NSMutableCharacterSet *set = [NSMutableCharacterSet characterSetWithCharactersInString:@"@!&"];
[set formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {
    // contains a-z, A-Z, 0-9 and &@! only - valid
} else {
    // invalid
}
  • 2
    FYI - The `alphanumericCharacterSet` includes much more than a-z, A-Z, 0-9. From the docs: *Informally, this set is the set of all characters used as basic units of alphabets, syllabaries, ideographs, and digits.* – rmaddy Jan 09 '13 at 09:04
2

The NSPredicate class is what you want

More info about predicate programming. Basically you want "self matches" (your regular expression). After that you can use the evaluateWithObject: method.

EDIT Easier way: (nevermind, as I am editing it wattson posted what I was going to)

borrrden
  • 33,256
  • 8
  • 74
  • 109
1

You can use the class NSRegularExpression to do this.

https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
1

You can also use NSRegularExpression to search your NSString, if it contains only the valid characters (or vice versa).

More info:

Search through NSString using Regular Expression

Use regular expression to find/replace substring in NSString

Community
  • 1
  • 1
Nevin
  • 7,689
  • 1
  • 23
  • 25
1
- (BOOL)validation:(NSString *)string  
{

   NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890abcdefghik"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return ([string isEqualToString:filtered]);
}

In your button action:

-(IBAction)ButtonPress{

 if ([self validation:activity.text]) {
    NSLog(@"Macth here");
}
else {
    NSLog(@"Not Match here");
}
}

Replace this "1234567890abcdefghik" with your letters with which you want to match

Aman Aggarwal
  • 3,754
  • 1
  • 19
  • 26
1
+(BOOL) validateString: (NSString *) string
{
    NSString *regex = @"[A-Z0-9a-z@!&]";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",  emailRegex];
    BOOL isValid = [test evaluateWithObject:string];
    return isValid;
}
Talha
  • 809
  • 4
  • 13
1

You can simply do it using NSMutableCharacterSet

NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:@"@?!"];
NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet]
NSString *trimmed = [ str componentsSeparatedByCharactersInSet:charactersToRemove];
if([trimmed length] != 0)
{
  //invalid string
}

Reference NSCharacterSet

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
1

You can use regex. If every thing fails use brute force like

 unichar c[yourString.length];
         NSRange raneg={0,2};
        [yourString getCharacters:c range:raneg];

// now in for loop

    for(int i=0;i<yourString.length;i++)
    {
     if((c[i]>='A'&&c[i]<='Z')&&(c[i]=='@'||c[i]=='!'||c[i]=='&'))
       {
         //not the best or most efficient way but will work till you write your regex:P
       }


    }
amar
  • 4,285
  • 8
  • 40
  • 52