Reputation: 790
I have a code which checks if the user input is ALphanumeric only and checks the strength of the password inputted based on a criteria. A label will appear with a note if:
-Field is empty
-invalid character is used
and also displays if password is WEAK, MEDIUM, STRONG, and VERY STRONG
this.AlphaNumericOnly(this.jTextField1.getText(),this.warningLbl3);
this.passwordStrength(this.jTextField1.getText(),this.warningLbl4);
This method works fine if used in a jtextfield. However I want to use a jpasswordfield to hide user input.
I've already tried:
.toString();
String.valueOf();
and this loop:
char[] input=(this.jPasswordField1.getPassword());
final_pass = "";
for(char x : input) {
final_pass += x;
}
But the method cannot "check" the string I converted.
Here are my methods..
public void AlphaNumericOnly(String input,JLabel obj){
if(!"".equals(input)){
obj.setText(" ");
warning=false;
char c[] = input.toCharArray();
int count = 0;
for(int x=0; x<c.length; x++){
if((!Character.isAlphabetic(c[x]))&&(!Character.isDigit(c[x]))){// && c[x]!='-' && c[x]!='(' && c[x]!=')' && c[x]!='+'&& c[x]!='/'&& c[x]!='\\'){
count=+1;
}
}
if(count>0){
obj.setText("*Please use valid characters.");
warning=true;
}else{
obj.setText(" ");
warning=false;
}
}else{
obj.setText("*This Field cannot be left Empty.");
warning=true;
}
}
private void passwordStrength(String input,JLabel obj){
char c[] = input.toCharArray();
int count=0;
int notAlphaNumericCount=0;
for(int j=0;j<c.length;j++){
if(Character.isAlphabetic(c[j])){
if(Character.isUpperCase(c[j])){
count++;
}
}else if(Character.isDigit(c[j])){
}else{
obj.setText(" ");
warning=false;
notAlphaNumericCount++;
}
}
if(notAlphaNumericCount==0){
if(input.length()<1){
obj.setText(" ");
warning=false;
}else if(input.length()<4){
obj.setText("Password Strength: WEAK");
obj.setForeground(Color.red);
}else if(input.length()<8){
obj.setText("Password Strength: MEDIUM");
obj.setForeground(Color.blue);
}else if(input.length()<10){
obj.setText("Password Strength: STRONG");
obj.setForeground(Color.green);
}else if(count!=0){
obj.setText("Password Strength: VERY STRONG");
obj.setForeground(Color.orange);
}
}
}
EDIT: for a more visual understanding here is how I use this method:
username [Textfield input]- [obj label warning]
password [Textfield input]- [obj label warning]
[obj label which displays password strength]
Upvotes: 0
Views: 4676
Reputation: 5131
well, as the returning value of getPassword()
function is char array. you could easily convert it into a string via its constructor.
new String(this.jPasswordField1.getPassword());
though, personally, I think it would be better to change the passwordStrength
method's arguments to take a char array instead of String. because you only use the argument input
to convert it into a char array and to get its length.
And also, you will create a new String object every time you construct a String via this way.
Upvotes: 2