2

My Password should be Like :

"Password should contain at least one uppercase letter, one lowercase letter, one digit and one special character with minimum eight character length"

The Pattern I have used is : ^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$#!%*?&])[A-Za-z\\d$@$#!%*?&]{8,}

So, I have created a function as below in my Constant.java file :

public static Boolean passwordMatcher(TextInputLayout edtText,String string) {
    Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)(?=.*[$@$#!%*?&])[A-Za-z\\\\d$@$#!%*?&]{8,}");
    Matcher matcher = pattern.matcher(edtText.getEditText().getText().toString());
    boolean isMatched = matcher.matches();
    if (isMatched) {
        return true;
    }
    if (!isMatched) {
        edtText.setErrorEnabled(true);
        edtText.setError("" + string);
        edtText.setFocusable(true);
        return false;
    }
    return true;
}

and in my MainActivity.java file I have checked for validation as below :

if (!Constant.passwordMatcher(edtPassword, mContext.getResources().getString(R.string.error_activity_signup_password_invalid))) {
    return;
}

But, I am not getting success even if I have tried : 'Jaimin123#' as a my password. Always getting error set in my TextInputLayout.

What might be the issue ?

Thanks.

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
ZaptechDev Kumar
  • 164
  • 1
  • 14

4 Answers4

3

Try using below regex for password match.

^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$

This regex will check for below rules:

  1. At least one upper case letter
  2. At least one lower case letter
  3. At least one digit
  4. At least one special character
  5. Minimum 8 in length
Priyank Patel
  • 12,244
  • 8
  • 65
  • 85
1

Try this

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@#!%*?&]).{8,}$

If you don't want white space in password include (?=\S+$) also

Aldrin Joe Mathew
  • 472
  • 1
  • 4
  • 13
  • java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 50: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$#!%*?&]){8,}$ – ZaptechDev Kumar Apr 27 '17 at 06:29
1

Try this code:

public void checkPattern(String password) {     
    Pattern pattern = Pattern.compile("(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\\W).{8,}");
    Matcher matcher = pattern.matcher(password);
    boolean isMatched = matcher.matches();
    System.out.println(isMatched);
}
user320676
  • 394
  • 2
  • 19
0

Try

public boolean matchesPattern(String password) {        
    Pattern pattern = Pattern.compile("^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$");
    Matcher matcher = pattern.matcher(password);
    return matcher.matches();
}
PEHLAJ
  • 9,980
  • 9
  • 41
  • 53