Java 密码验证 8 位数字,包含大写、小写和特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36097097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Password validate 8 digits, contains upper,lowerCase,and a special Character
提问by Progamminnoob
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
1.长度至少为 8 位
2.Have an uppercase
2.有一个大写
3.Have a lowercase
3.有一个小写
4.Have special digit
4.有特殊数字
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.
此外,另一个问题是,例如,假设用户输入bob123
作为他们的密码。
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).
在上面的例子中,它缺少一个大写字母和一个符号(*&^..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?
每次用户输入密码时,如何将其添加到打印出来,直到他们获得正确的密码以通过代码的所有规范?
采纳答案by Ankur
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;
}
回答by Stephen C
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 ....
提示2:我认为你需要计算各种字符类中的字符,然后......
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)
我怎样才能让循环告诉用户它需要一个正确的密码?对于上面的例子,它缺少一个大写字母和一个符号(*&^..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)
提示:您的 isValid 方法需要“告诉”某人或某事密码无效的原因。想想它是怎么做到的。(提示2:我可以想到三种不同的方法:异常、返回值、打印)
回答by Ankur
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;
}
回答by Ankur Pathak
Use this bean validation library for password validation:
使用此 bean 验证库进行密码验证:
https://github.com/ankurpathak/password-validationhttps://mvnrepository.com/artifact/com.github.ankurpathak.password/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:
它提供了许多处理密码验证的约束,并且在不久的将来还会添加更多约束:
- ContainDigit: To validate if password contain specified number of digits.
- ContainLowercase: To validate if password contain specified number of lowercase.
- ContainSpecial: To validate if password contain specified number of special symbols.
- ContainUppercase: To validate if password contain specified number of uppercase.
- NotContainWhitespace: To validate should not have any whitespace.
- 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).
- ContainDigit:验证密码是否包含指定位数。
- ContainLowercase:验证密码是否包含指定数量的小写字母。
- ContainSpecial:验证密码是否包含指定数量的特殊符号。
- ContainUppercase:验证密码是否包含指定数量的大写字母。
- NotContainWhitespace:验证不应该有任何空格。
- PasswordMatches:验证密码和确认密码是否相等。您还可以使用标志 showErrorOnConfirmPassword(默认为 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.
默认情况下,所有约束都忽略空白,以便 NotBlank 标准 bean 验证约束单独报告它,并且我们可以使用每个约束的 ignoreBlank(默认为 true) 标志。
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; }
回答by akash shah
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);
}
}
}