public String checkStrength(String password) { String result = ""; //int strength = 0; //If password contains both lower and uppercase characters, increase strength value. Pattern ps = Pattern.compile("(?=.*[a-z])"); Pattern pl = Pattern.compile("(?=.*[A-Z])"); Matcher ms = ps.matcher(password); Matcher ml = pl.matcher(password); //System.out.println(ms.matches()); if(!ms.matches()) { //strength += 1; result += "lowercase letter not foundn"; } if(!ml.matches()) { //strength += 1; result += "uppercase letter not foundn"; } //If it has numbers and characters, increase strength value. Pattern p1 = Pattern.compile("(?=.*[a-z])(?=.*[A-Z])"); Pattern p2 = Pattern.compile("(?=.*[0-9])"); Matcher m1 = p1.matcher(password); Matcher m2 = p2.matcher(password); if(m1.matches() == false || m2.matches() == false) { //strength += 1; result += "number and character combo not foundn"; } //If it has one special character, increase strength value. Pattern p3 = Pattern.compile("^(?=.*[@#$%^&+=])"); Matcher m3 = p3.matcher(password); if(!m3.matches()) { //strength += 1; result += "special character not foundn"; } //check length of password if (password.length() < 8) { //strength += 1; result += "length must be minimum 8.n"; } //now check strength // if(strength < 2) { // //return "Weak"; // } return result; }
i have used regex for password validation. i am using servlet for this validation but there is some issue arising. this method isnt working. it returns all the errors even if some conditions are satisfied. help! if anything else reqd i will add it just ask.
input –
valid
expected output –
uppercase letter not found number and character combo not found special character not found length must be minimum 8.
actual output –
lowercase letter not found uppercase letter not found number and character combo not found special character not found length must be minimum 8.
Advertisement
Answer
Your pattern are incomplete. Add .+
at the end of each pattern.
Example: change
Pattern.compile("(?=.*[a-z])"); Pattern.compile("(?=.*[A-Z])");
to
Pattern.compile("(?=.*[a-z]).+"); Pattern.compile("(?=.*[A-Z]).+");