I want to make a registration system in java. It's in a very good progress. I only have one specific problem. The password weakness. I made that, tha password must be longer than 8 character with a simple
if(password.getText().length() > 8) { error message }
I also put a condition just like that:
if(... < 8 || !(password.getText().contains("1"))) { error message }
But with this condition it only accept the password if your password for example: asdfghjk1 So I tried the condition with a lot of || condition like !....contains("2")..|| !..contains("9")
But with theese conditions it only works when the password is: 123456789 But what i really want to do is a password, that longer than 8 character, contains at least one capital and at least one number. Is that any way to do that? By the way I use Java swing.
The best way to solve this problem is to use Regex. Here I am making an example for you of how to use regex to check password.
import java.util.regex.*;
class GFG {
// Function to validate the password.
public static boolean
isValidPassword(String password)
{
// Regex to check valid password.
String regex = "^(?=.*[0-9])"
+ "(?=.*[a-z])(?=.*[A-Z])"
+ "(?=.*[@#$%^&+=])"
+ "(?=\\S+$).{8,20}$";
// Compile the ReGex
Pattern p = Pattern.compile(regex);
// If the password is empty
// return false
if (password == null) {
return false;
}
// Pattern class contains matcher() method
// to find matching between given password
// and regular expression.
Matcher m = p.matcher(password);
// Return if the password
// matched the ReGex
return m.matches();
}
// Driver Code.
public static void main(String args[])
{
// Test Case 1:
String str1 = "Thuans@portal20";
System.out.println(isValidPassword(str1));
// Test Case 2:
String str2 = "DaoMinhThuan";
System.out.println(isValidPassword(str2));
// Test Case 3:
String str3 = "Thuan@ portal9";
System.out.println(isValidPassword(str3));
// Test Case 4:
String str4 = "1234";
System.out.println(isValidPassword(str4));
// Test Case 5:
String str5 = "Gfg@20";
System.out.println(isValidPassword(str5));
// Test Case 6:
String str6 = "thuan@portal20";
System.out.println(isValidPassword(str6));
}
}
Output: true false false false false false
Also you can refer to similar topics by following the link below: