19

Hi I am very new for android and in my app I have Validations for Change password page.

That means the Password must contain minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character, for this I tried the code below, but it's not working.

Please help me.

if(!isPasswordValidMethod(newPassword.getText().toString())){
           System.out.println("Not Valid");

                }else{

        System.out.println("Valid");
    }



     // Validate password
        private boolean isPasswordValidMethod(String password) {

            String yourString = newPassword.getText().toString();

            System.out.println("yourString is =" + yourString);

            boolean isValid = false;

            // ^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$
            // ^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$

            String expression = "^(?=.*[A-Za-z])(?=.*\\\\d)(?=.*[$@$!%*#?&])[A-Za-z\\\\d$@$!%*#?&]{8,}$";
            CharSequence inputStr = password;

            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(inputStr);
            if (matcher.matches()) {
                System.out.println("if");
                isValid = true;
            }else{
                System.out.println("else");
            }
            return isValid;
        }
Elydasian
  • 2,016
  • 5
  • 23
  • 41
Krish
  • 4,166
  • 11
  • 58
  • 110
  • Maybe this answer will help you: http://stackoverflow.com/questions/9962382/password-validation-adding-additional-requirments – Francisco Nin Apr 12 '16 at 13:07

10 Answers10

38

try following Code

 //*****************************************************************
public static boolean isValidPassword(final String password) {

    Pattern pattern;
    Matcher matcher;
    final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.*[@#$%^&+=!])(?=\\S+$).{4,}$";
    pattern = Pattern.compile(PASSWORD_PATTERN);
    matcher = pattern.matcher(password);

    return matcher.matches();

}

And change your code to this

   if(newPassword.getText().toString().length()<8 &&!isValidPassword(newPassword.getText().toString())){
        System.out.println("Not Valid");
      }else{
       System.out.println("Valid");
    }
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41
mdDroid
  • 3,135
  • 2
  • 22
  • 34
  • 1
    if(newPassword.getText().toString().length()<8 ||!isValidPassword(newPassword.getText().toString())){ System.out.println("Not Valid"); – Krish Apr 12 '16 at 13:28
  • that is validate condition – Krish Apr 12 '16 at 13:28
  • 1
    minimum 8 characters means it must be "&&" not || – mdDroid Apr 12 '16 at 13:42
  • What would be conditions for this pattern like password must contain min 8 characters, must be alpha numeric,must contain at least one symbol. Like this? @mdDroid – Sid Nov 12 '16 at 09:31
  • For anyone that wants to know ... The regex represents the need for user to enter atleast `1 Uppercase, 1 Number and 1 Symbol`. – Asghar Musani Oct 24 '19 at 16:14
7
public static boolean isValidPassword(String s) {
            Pattern PASSWORD_PATTERN
                    = Pattern.compile(
                    "[a-zA-Z0-9\\!\\@\\#\\$]{8,24}");

            return !TextUtils.isEmpty(s) && PASSWORD_PATTERN.matcher(s).matches();
        }

to use it,

if(isValidPassword(password)){ //password valid}

You can set whatever symbol that you allowed here

yuzuriha
  • 465
  • 1
  • 8
  • 18
2
public static boolean passwordCharValidation(String passwordEd) {
    String PASSWORD_PATTERN = "^(?=.*[A-Z])(?=.*[@_.]).*$";
    Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
    Matcher matcher = pattern.matcher(passwordEd);
    if (!passwordEd.matches(".*\\d.*") || !matcher.matches()) {
        return true;
    }
    return false;
}
Nitesh Pareek
  • 362
  • 2
  • 10
  • Is you answer full-fill :It contains minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character.Thanks –  Apr 12 '16 at 13:17
  • yes Firstly check passwordEd length greater then 8 if(passwordEd.length() > 8); – Nitesh Pareek Apr 12 '16 at 13:23
2
  String validPassword = "12345";
                     _Password_String = Password.getText().toString();
                    Matcher matcher = Pattern.compile(validPassword).matcher(_Password_String);
                    if (matcher.matches()) {
                        Log.e("d11", _Password_String);
                        Toast.makeText(getActivity(), "Password Match", Toast.LENGTH_LONG).show();
                        getFragmentManager().popBackStack();


                    } else {
                        Password.setError("Password");
                        Toast.makeText(getActivity(), "Password not Match", Toast.LENGTH_LONG).show();
                    }
1

Try this it works

   public static boolean isPasswordValidMethod(final String password) {

    Pattern pattern;
    Matcher matcher;
    final String PASSWORD_PATTERN = "^(?=.*[A-Za-z])(?=.*\\\\d)(?=.*[$@$!%*#?&])[A-Za-z\\\\d$@$!%*#?&]{8,}$""
    pattern = Pattern.compile(PASSWORD_PATTERN);
    matcher = pattern.matcher(password);

    return matcher.matches();

}
Arpit Patel
  • 7,212
  • 5
  • 56
  • 67
Pitty
  • 1,907
  • 5
  • 16
  • 34
1

You can solve this without using Regex. Here is the code part :

private fun hasUpperCase(data: CharSequence): Boolean {
    val password = data.toString()
    return password.toLowerCase(Locale.ROOT) == password
}

private fun hasLowerCase(data: CharSequence): Boolean {
    val password = data.toString()
    return password.toUpperCase(Locale.ROOT) == password
}
Umut Can
  • 41
  • 2
0

easy piece of code for email field validation and password validation and check for minimum 8 characters in password field.

  if (isValidEmail(et_regemail.getText().toString())&&etpass1.getText().toString().length()>7){
      if (validatePassword(etpass1.getText().toString())) {
      Toast.makeText(getApplicationContext(),"Go Ahead".....
      }
      else{

       Toast.makeText(getApplicationContext(),"InvalidPassword".....
       }

}else{

 Toast.makeText(getApplicationContext(),"Invalid Email".....
}


public boolean validatePassword(final String password){
    Pattern pattern;
    Matcher matcher;
    final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.* 
    [@#$%^&+=!])(?=\\S+$).{4,}$";
    pattern = Pattern.compile(PASSWORD_PATTERN);
    matcher = pattern.matcher(password);

    return matcher.matches();
}

public final static boolean isValidEmail(CharSequence target) {
    if (target == null)
        return false;

    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
Syed Danish Haider
  • 1,334
  • 11
  • 15
0

Simple and sort, just use below method for checking valid password,

public static boolean isValidPassword(String password) {
    Matcher matcher = Pattern.compile("((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{4,20})").matcher(password);
    return matcher.matches();
}

and you can use this method as below

          if (!isValidPassword(edtPassword.getText().toString())) {
                errorDialog("Password must contain mix of upper and lower case letters as well as digits and one special charecter(4-20)");
                }
varotariya vajsi
  • 3,965
  • 37
  • 39
0
public static boolean isPasswordValidMethodTrueOrFalse(final String password) {

    Pattern pattern;
    Matcher matcher;
    final String THE_REAL_PASSWORD_PATTERN = "^(?=.*[A-Za-z])(?=.*\\\\d)(?=.*[$@$!%*#?&])[A-Za-z\\\\d$@$!%*#?&]{8,}$""
    pattern = Pattern.compile(THE_REAL_PASSWORD_PATTERN);
    matcher = pattern.matcher(password);

    return matcher.matches(); 
}
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
  • Please add explanations. – Syscall Jan 21 '23 at 06:45
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 23 '23 at 23:00
-3

Passwords do not match

if  (password.getText().toString() != reEnteredPassword.getText().toString()) {
//not match
}

For Empty Fields

if (password.getText().toString().isEmpty() || reEnteredPassword.getText().toString().isEmpty()) {
//Fieds empty error message

Less than 8 characters

if ((password.getText().toString().length() < 8) || (reEnteredPassword.getText().toString().length() < 8)) {
// less than 8 characters error message
}

Not having special characters

if (!password.getText().toString().matches( "^(?=.*[0-9])(?=.*[a-z])(?=.*[!@#$%^&*+=?-]).{8,15}$") || !reEnteredPassword.getText().toString().matches( "^(?=.*[0-9])(?=.*[a-z])(?=.*[!@#$%^&*+=?-]).{8,15}$")){
//not having special characters error message
}
MoniFern
  • 37
  • 1
  • 3
  • 1
    While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Apr 12 '20 at 16:01