Harish
Harish

Reputation: 2512

NSString value validation in iOS

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

Upvotes: 3

Views: 2306

Answers (9)

amar
amar

Reputation: 4343

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
       }


    }

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107191

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

Upvotes: 1

Talha
Talha

Reputation: 809

+(BOOL) validateString: (NSString *) string
{
    NSString *regex = @"[A-Z0-9a-z@!&]";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",  emailRegex];
    BOOL isValid = [test evaluateWithObject:string];
    return isValid;
}

Upvotes: 1

Aman Aggarwal
Aman Aggarwal

Reputation: 3754

- (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

Upvotes: 1

user529758
user529758

Reputation:

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
}

Upvotes: 3

Nevin
Nevin

Reputation: 7819

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

Upvotes: 1

wattson12
wattson12

Reputation: 11174

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

Upvotes: 3

borrrden
borrrden

Reputation: 33421

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)

Upvotes: 2

Related Questions