Check whether an NSString contains a special character and a digit

前端 未结 5 1596
别那么骄傲
别那么骄傲 2020-12-31 18:56

I need to check whether a string contains one uppercase letter, one lower case letter, one integer and one special character. How do I check?

5条回答
  •  一生所求
    2020-12-31 19:07

    Here is what I would do. Create Regular expressions for every condition you need to check if corresponding value present or not.

    i.e. Regular Expression to check if it has one uppercase letter, one lower case letter , one integer and one special character, and so on.

    and then use the same string to check against every regular expression if all of them return true you have winner if not then string doesn't match to your criteria.

    // Example for the Validating UpperCaseLetter do same for all others with matching regular expression.

    -(BOOL) validateOneUpperCaseLetter:(NSString *)string {
    if ((string == nil) || ([string isEqualToString: @""])) {
        return NO;
    }
    
    // Change this regEx to one you needed. // this one validates for the "name".  
    NSString *regEx = @"^[a-zA-Z]+(([\\'\\,\\.\\ -][a-zA-Z])?[a-zA-Z]\\s*)*$";
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regEx];
    BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject: string];
    
    if (!myStringMatchesRegEx) {
        return NO;
    }
    return YES;}
    

提交回复
热议问题