1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package utils;
import java.util.regex.Pattern;
public class PasswordValidator {
// Regex rule: At least 8 chars, one upper, one lower, one digit, one special char
private static final String PASSWORD_PATTERN =
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@#$%^&*!?])[A-Za-z\\d@#$%^&*!?]{8,}$";
private static final Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
/**
* Validate password strength
* @param password the password input
* @return true if valid, false otherwise
*/
public static boolean isValid(String password) {
if (password == null || password.trim().isEmpty()) {
return false;
}
return pattern.matcher(password).matches();
}
/**
* Validate only basic length (if you want a simpler rule)
*/
public static boolean isMinLength(String password, int length) {
return password != null && password.length() >= length;
}
}
Note: Regular expression (Regex)
1
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&*!?])[A-Za-z\d@#$%^&*!?]{8,}$
This is a Java-style regex (works with String.matches() or Pattern.compile()), commonly used for password validation. It ensures:
(?=.*[a-z])
: at least one lowercase letter(?=.*[A-Z])
: at least one uppercase letter(?=.*\d)
: at least one digit(?=.*[@#$%^&*!?])
: at least one special character[A-Za-z\d@#$%^&*!?]{8,}
: only allowed characters, length ≥ 8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Validate password format first
// if (!PasswordValidator.isMinLength(password, 8)) {
// request.setAttribute("loginError", "Password must be at least 8 characters long.");
// request.setAttribute("contentPage", "login_form_content.jsp");
// request.getRequestDispatcher("views/pages/login.jsp").forward(request, response);
// return;
// }
if (!PasswordValidator.isValid(password)) {
request.setAttribute("loginError", "Password must contain uppercase, lowercase, number, special char, and be at least 8 characters.");
request.setAttribute("contentPage", "login_form_content.jsp");
request.getRequestDispatcher("views/pages/login.jsp").forward(request, response);
return;
}
// Authenticate with database
String uName = userDAO.CheckUser(username, password);
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.sendRedirect("home");
} else {
request.setAttribute("loginError", "Invalid username or password.");
request.getRequestDispatcher("views/pages/login.jsp").forward(request, response);
}
}
1
2
3
4
5
6
7
8
<!-- ... -->
<button type="submit" class="btn btn-primary">Login</button>
<p style="color:red;"><%= request.getAttribute("loginError") != null ? request.getAttribute("loginError") : "" %></p>
<!-- ... -->
1
2
3
UPDATE Users
SET Password = '123456x@X'
WHERE Username = 'admin';