6

So I wrote a method that makes the user enter a password and this password must pass the following specs:

1. Be at least 8 digits long

2. Have an uppercase

3. Have a lowercase

4. Have special digit

I'm not sure as to why when I input it, the output doesn't account for the special Character and throws an error.

Here is my code so far:

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Please enter a given  password : ");
    String passwordhere = in.nextLine();
    System.out.print("Please re-enter the password to confirm : ");
    String confirmhere = in.nextLine();
    System.out.println("your password is: " + passwordhere);

    while (!passwordhere.equals(confirmhere) || !isValid(passwordhere)) {
        System.out.println("The password entered here  is invalid");
        System.out.print("Please enter the password again.it must be valid : ");
        String Passwordhere = in.nextLine();
        System.out.print("Please re-enter the password to confirm : ");

    }
}

public static boolean isValid(String passwordhere) {

    if (passwordhere.length() < 8) {
        return false;
    } else {

        for (int p = 0; p < passwordhere.length(); p++) {
            if (Character.isUpperCase(passwordhere.charAt(p))) {
            }
        }
        for (int q = 0; q < passwordhere.length(); q++) {
            if (Character.isLowerCase(passwordhere.charAt(q))) {
            }
        }
        for (int r = 0; r < passwordhere.length(); r++) {
            if (Character.isDigit(passwordhere.charAt(r))) {
            }
        }
        for (int s = 0; s < passwordhere.length(); s++) {
            if (Character.isSpecialCharacter(passwordhere.charAt(s))) {
            } 
            }
            return true;
        }
}

Also, another problem is for example, lets say the user enter bob123 as their password.

How can I get the loop to tell the user what It needs to be a correct password?

On the example above it is missing a Capital Letter and a symbol(*&^..etc).

How can I add this to print out each time the user makes a password and until they get the right password to pass all specs of the code?

codependent
  • 23,193
  • 31
  • 166
  • 308
Progamminnoob
  • 293
  • 3
  • 4
  • 14
  • @Programminnoob Please do some research on password validation with regex and let me know what you find. Character.isSpecialCharacter is not a function and the easiest way to check for a special character is with a regular expression, so you might as well learn how to do this correctly – OneCricketeer Mar 19 '16 at 03:05
  • Please refer to http://stackoverflow.com/a/12885952/2308683 – OneCricketeer Mar 19 '16 at 03:49
  • @cricket_007 how can I impliment any of those into my code. ' return (s == null) ? false : s.matches("[^A-Za-z0-9 ]");' maybe this line? – Progamminnoob Mar 19 '16 at 04:04
  • That replaces your non-existant `Character.isSpecialCharacter` – OneCricketeer Mar 19 '16 at 04:06
  • do I use it as a seperate method? or do I make it a loop? @cricket_007 – Progamminnoob Mar 19 '16 at 04:08
  • I'm not convinced that the regex approach works. I read the requirement as "at least one upper case letter, at least one lower case letter, and at least one special character". That is hard to express as a regex. – Stephen C Mar 19 '16 at 04:12
  • i think im even more confused now haha @StephenC – Progamminnoob Mar 19 '16 at 04:15
  • Well look at my updated answer. *"Hint 2: I think you need to count the characters in the various character classes and then ...."* – Stephen C Mar 19 '16 at 04:32
  • This sounds remarkably like [this](http://stackoverflow.com/questions/36094808/how-to-ask-for-a-password-with-unique-complexities-and-exceptions-in-joptionpane/36095340#36095340) – MadProgrammer Mar 19 '16 at 05:35

5 Answers5

15

You should have clearly mention your requirement I was not aware of your requirement. Please find my below solution`

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Please enter a given  password : ");
    String passwordhere = in.nextLine();
    System.out.print("Please re-enter the password to confirm : ");
    String confirmhere = in.nextLine();

    List<String> errorList = new ArrayList<String>();

    while (!isValid(passwordhere, confirmhere, errorList)) {
        System.out.println("The password entered here  is invalid");
        for (String error : errorList) {
            System.out.println(error);
        }

        System.out.print("Please enter a given  password : ");
        passwordhere = in.nextLine();
        System.out.print("Please re-enter the password to confirm : ");
        confirmhere = in.nextLine();
    }
    System.out.println("your password is: " + passwordhere);

}

public static boolean isValid(String passwordhere, String confirmhere, List<String> errorList) {

    Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
    Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
    Pattern lowerCasePatten = Pattern.compile("[a-z ]");
    Pattern digitCasePatten = Pattern.compile("[0-9 ]");
    errorList.clear();

    boolean flag=true;

    if (!passwordhere.equals(confirmhere)) {
        errorList.add("password and confirm password does not match");
        flag=false;
    }
    if (passwordhere.length() < 8) {
        errorList.add("Password lenght must have alleast 8 character !!");
        flag=false;
    }
    if (!specailCharPatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one specail character !!");
        flag=false;
    }
    if (!UpperCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one uppercase character !!");
        flag=false;
    }
    if (!lowerCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one lowercase character !!");
        flag=false;
    }
    if (!digitCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one digit character !!");
        flag=false;
    }

    return flag;

}
Ankur
  • 192
  • 5
0

I'm not sure as to why when I output it the output doesn't account for the special Character and throws an error.

Hint: take a look at this fragment:

    for (int p = 0; p < passwordhere.length(); p++) {
        if (Character.isUpperCase(passwordhere.charAt(p))) {
        }
    }

What does it DO when it sees an uppercase character?

Hint 2: I think you need to count the characters in the various character classes and then ....

How can I get the loop to tell the user what It needs to be a correct password? for the example above it is missing a Capital letter and a symbol(*&^..etc)

Hint: your isValid method needs to "tell" someone or something why the password is invalid. Think about how it could do that. (Hint 2: I can think of three different ways to do it: exception, return value, print)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • it loops to see if the password has an uppercase letter..? – Progamminnoob Mar 19 '16 at 02:54
  • @Programminnoob Yes, but what happens **when** there is a capital letter? What is **inside** the if statement? – OneCricketeer Mar 19 '16 at 02:57
  • it tells the boolean to return true? :o @cricket_007 – Progamminnoob Mar 19 '16 at 02:58
  • and for the second part of stephens comment, should I just add a print statement inside the loop like: 'for (int p = 0; p < 'passwordhere.length(); p++) {' 'if (Character.isUpperCase(passwordhere.charAt(p))) {' ' System.out.println("password must contain an upper case letter.");' } – Progamminnoob Mar 19 '16 at 02:59
  • @Programminnoob nothing is returning inside an empty if statement. You are looping and checking for capitals correctly, but not doing anything about it because the body of the if statement is empty and there is no else statement (hint: a non uppercase letter is lowercase... You don't need two loops) – OneCricketeer Mar 19 '16 at 03:01
  • good point haa @cricket_007 so i deleted the lower case loop, – Progamminnoob Mar 19 '16 at 03:03
  • I read up on what you said but still not really sure how to implement it @cricket_007 – Progamminnoob Mar 19 '16 at 03:37
  • @Programminnoob does `password.matches("[a-zA-Z\d]{8}")` make sense to you? If not, please keep reading – OneCricketeer Mar 19 '16 at 03:40
  • yes that does make sense, its saying that all lowercase and upcase letters but what about symbols :o @cricket_007 – Progamminnoob Mar 19 '16 at 03:47
  • *"... should I just add a print statement inside the loop like ..."*. That is for you to figure out. I'm helping you to do your own homework, not doing it for you. – Stephen C Mar 19 '16 at 04:01
0

Use this bean validation library for password validation:

https://github.com/ankurpathak/password-validation https://mvnrepository.com/artifact/com.github.ankurpathak.password/password-validation

It provides many constraint to deal with password validation and many more will be added in near future:

  1. ContainDigit: To validate if password contain specified number of digits.
  2. ContainLowercase: To validate if password contain specified number of lowercase.
  3. ContainSpecial: To validate if password contain specified number of special symbols.
  4. ContainUppercase: To validate if password contain specified number of uppercase.
  5. NotContainWhitespace: To validate should not have any whitespace.
  6. PasswordMatches: To validate if password and confirm password are equal. You can move also move constraint to confirm password field by using flag showErrorOnConfirmPassword (default is true).

All the constraints by default ignore blank so that it will be reported separately by NotBlank standard bean validation constraint and same can we turned of using ignoreBlank(true by default) flag of each constraint.

Small example to use the library is:


    @PasswordMatches
    public class PasswordDto {
     @Size(min = 8, max = 30)
     @NotContainWhitespace
     @ContainSpecial
     @ContainDigit
     private String password;
     @NotBlank
     private String confirmPassword;
    }

-1

Hi Please check below code it may help you

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Please enter a given  password : ");
    String passwordhere = in.nextLine();
    System.out.print("Please re-enter the password to confirm : ");
    String confirmhere = in.nextLine();
    System.out.println("your password is: " + passwordhere);
    List<String> errorList=isValid(passwordhere,confirmhere);
    while (!errorList.isEmpty()) {
        System.out.println("The password entered here  is invalid");
        for(String error : errorList){
            System.out.println(error);
        }
        String Passwordhere = in.nextLine();
        System.out.print("Please re-enter the password to confirm : ");

    }

}

public static List<String> isValid(String passwordhere, String confirmhere) {

    List<String> errorList = new ArrayList<String>();

    Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
    Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
    Pattern lowerCasePatten = Pattern.compile("[a-z ]");
    Pattern digitCasePatten = Pattern.compile("[0-9 ]");

    if (!passwordhere.equals(confirmhere)) {
        errorList.add("password and confirm password does not match");
    }
    if (passwordhere.length() <= 8) {
        errorList.add("Password lenght must have alleast 8 character !!");
    }
    if (!specailCharPatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one specail character !!");
    }
    if (!UpperCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one uppercase character !!");
    }
    if (!lowerCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one lowercase character !!");
    }
    if (!digitCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one digit character !!");
    }

    return errorList;

}
Ankur
  • 192
  • 5
  • this codeworks but if i have a password like Bob123 and it doesn't have a special character it will tell me that I need a special character but then it doesn't let me restart the password part. how can i fix it to restart the first question and let the user type a new password? – Progamminnoob Mar 19 '16 at 04:49
-1
import javax.swing.JOptionPane;

    public class Validation {   

    static String password;

    public static boolean IsValidInput(String s) {

     boolean status = false;    
     char [] array = s.toCharArray();
     int lower=0, upper=0, digits=0;

     if (s.length() > 8) 
     status = true;

      for ( int i = 0;  i < array.length; i++) {
       if(Character.isDigit(array[i]))
          digits++;
       if(Character.isLowerCase(array[i]))
          lower++;
       if(Character.isUpperCase(array[i]))
          upper++;
     }

       if ( !(lower  > 0 ))
       status = false;

       if ( !(upper  > 0 ))
       status = false;

       if ( !(digits > 0 ))
       status = false;

       return status;
     }     

     public static void  setPassword(String p) {
     if (IsValidInput(p)) {
      password = p;
     JOptionPane.showMessageDialog( null, " Your Password is accepted -" + p);
     }

     else {
     password ="";
     JOptionPane.showMessageDialog( null, " Your  Password is  not accepted -" + p);
     }
     }

    }
Ajay Takur
  • 6,079
  • 5
  • 39
  • 55