validate alphanumeric value in UITextField

ios7, objective-c

Solution

How about using regular expression:

-(BOOL)isAlphaNumericOnly:(NSString *)input 
{
    NSString *alphaNum = @"[a-zA-Z0-9]+";
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", alphaNum];

    return [regexTest evaluateWithObject:input];
}

and then use it

if([self isAlphaNumeric:str])
{
    NSLog(@"IT IS ALPHA NUMERIC STRING");

}

edit The same technique can be used to validate passwords, you need only better regex:

-(BOOL)isPasswordStrong:(NSString *)password {
/*
8-20 chars
at least one letter
at least one number OR special character
no more than 3 repeated characters
*/
        NSString *strongPass= @"^(?!.*(.)\\1{3})((?=.*[\\d])(?=.*[A-Za-z])|(?=.*[^\\w\\d\\s])(?=.*[A-Za-z])).{8,20}$";;
        NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strongPass];

        return [regexTest evaluateWithObject:password];
}

using the regular expression you can create different rules but this can give you a headstart,

Problem

I want alphanumeric value in textfield.If user enter only character or number then sending massage.Even no special characters acceptable. ``` NSString *str = askIdTxt.text; NSCharacterSet *alphanumericSet = [NSCharacterSet alphanumericCharacterSet]; NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet]; BOOL isAlphaNumericOnly = [[str stringByTrimmingCharactersInSet:alphanumericSet] isEqualToString:@""] && ! [[str stringByTrimmingCharactersInSet:numberSet] isEqualToString:@""]; if (isAlphaNumericOnly) { NSLog(@"isAplhaNumericOnly: %@",(isAlphaNumericOnly? @"Yes":@"No")); } ``` This is always returning true. I am not getting what is wrong in this.

Original source