JRafaelM
JRafaelM

Reputation: 881

Identify chars in alphabetical sequence OBJ-C

I'm writting an iOS app that has a signup section. My client has these awful rules about validation that's driving me crazy. The newest rule is like this: Do not accept more than 3 chars in alphabetical order such as: "abcd", "eFgH", "jklM".

But i can accept numbers in sequence like "1234", "3456"...

To solve these kind of problemas I'm already using NSPredicate, and NSRegularExpression. But I have no idea of a regex to identify these chars, so I'm asking for your help.

Do anyone have an idea of how to solve this problem?

Upvotes: 1

Views: 102

Answers (2)

rob mayoff
rob mayoff

Reputation: 385690

Start with the simplest thing that could possibly work:

BOOL hasAlphabetSequence(NSString *s, int sequenceLength) {
    static NSString *const alphabet = @"abcdefghijklmnopqrstuvwxyz";
    s = [s lowercaseString];
    for (int i = 0, l = (int)alphabet.length - sequenceLength; i < l; ++i) {
        NSString *sequence = [alphabet substringWithRange:NSMakeRange(i, sequenceLength)];
        if ([s rangeOfString:sequence].location != NSNotFound) {
            return YES;
        }
    }
    return NO;
}

Upvotes: 1

A-Live
A-Live

Reputation: 8944

Let me congratulate you they have not yet noticed the keyboard doesn't have alphabetical layout :)

NSString * str = [@"01234abcdsfsaasgAWEGFWAE" lowercaseString]; // make it a lower case string as you described it not case-sensitive
const char * strUTF8 = [str UTF8String]; // get char* password text for the numerical comparison

BOOL badPassword = NO;
int charIndex = 0;
int badHitCount = 0;
const int len = strlen(strUTF8);
char previousChar = strUTF8[0]; // the app is going to crash here with an empty string

// check the password
while (charIndex < len) {
    char currentChar = strUTF8[charIndex++];
    if (currentChar - previousChar == 1 && (currentChar >= 57 || currentChar <= 48)) 
    // 57 is the character '9' index at UTF8 table, letters are following this index, some characters are located before 48's '0' character though
        badHitCount++;
    else
        badHitCount = 0;
    previousChar = currentChar;

    if (badHitCount >= 3) {
        badPassword = YES;
        break;
    }
}

if (badPassword) {
    NSLog(@"You are a Bad User !");
} else {
    NSLog(@"You are a Good User !");
}

Upvotes: 2

Related Questions