Password validation in UITextField in iOS

前端 未结 11 1115
有刺的猬
有刺的猬 2020-12-01 12:54

I have 1 UITextfield for password in my iPhone application.

I want to validate this textfield with the following validation.

  • Must be at le
11条回答
  •  伪装坚强ぢ
    2020-12-01 13:38

    You can also do this by using Regex. Here are few example I am providing for you:

    // *** Validation for Password ***
    
        // "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$" --> (Minimum 8 characters at least 1 Alphabet and 1 Number)
        // "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&])[A-Za-z\\d$@$!%*#?&]{8,16}$" --> (Minimum 8 and Maximum 16 characters at least 1 Alphabet, 1 Number and 1 Special Character)
        // "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$" --> (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet and 1 Number)
        // "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}" --> (Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
        // "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,10}" --> (Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character)
    

    Fourth from the list is your case, following code snippet shows how to use it:

    -(BOOL)isValidPassword:(NSString *)passwordString
    {
        NSString *stricterFilterString = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{10,}";
        NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
        return [passwordTest evaluateWithObject:passwordString];
    }
    

    Using the method:

    if(![self isValidPassword:txtPassword.text]) {
        /* Show alert: "Password must be minimum 10 characters,
           at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 
           1 Number and 1 Special Character" */
    }
    else {
        // Password is valid
    }
    

提交回复
热议问题