Hugo Santos
Hugo Santos

Reputation: 113

String Validation using REGEX with Objective-C (password use case)

I am trying to validate a password through the usage of regex with objective-c. I have searched through about 4-5 different stack overflow answers on this topic and for some reason it still gives me the same outcome.

The string needs to contain a minimum of:

This could also be a logic error, which it would tear my soul apart, been spending a few hours on this. I am 'fairly' certain it isn't but well.. it could be.

Here is my validation function:

- (BOOL) validPassword:(NSString *) passwordString {
    NSString *passwordRegex = @"(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{8,20}"; //regex string condition
    NSPredicate *passwordValidation = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passwordRegex];
    return [passwordValidation evaluateWithObject:passwordRegex];
}

Here I am calling the function:

if (![self validPassword:self.passwordTextField.text]) { //if password is invalid
        //display feedback to user
    } else { //if password is valid
        //create a user
    }

Thank you in advance!

Cheers,

Upvotes: 1

Views: 149

Answers (1)

Larme
Larme

Reputation: 26016

You are checking if the pattern is compatible with itself instead of checking the password:

return [passwordValidation evaluateWithObject:passwordRegex];

=>

return [passwordValidation evaluateWithObject:passwordString];

If you'd have named your variables differently:

- (BOOL)validPassword:(NSString *)stringToValidate {
    NSString *pattern = @"(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{8,20}"; //regex string condition
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [predicate evaluateWithObject:stringToValidate];
}

It might have been more obvious.

Since you are in a small method with 2 vars & 1 params, naming your var starting with the same sequence (passwordFollwedBySomething), it's harder to see when you misplaced one of them.

Upvotes: 1

Related Questions