以下是我验证PasswordField的示例。
此代码将验证密码是否匹配,如果密码与数据库匹配,则返回3的整数。
/*
* loginValidator method
* The objective of this method is to return the integer value
* If the return value is 0 that means the password field is wrong from the database
* If the return value is 1 that means the email field are not met
* If the return value is 2 that means the password field are not met
* If the return value is 3 that means the password and email are met and is correct from the database
*/
public static int loginValidator(String email, String password) {
// Checks the email
Pattern emailField = Pattern.compile(".+@.+\\.[a-z]+");
Matcher m = emailField.matcher(email);
boolean legitEmail = m.matches();
// Checks the password
/*
Pattern passwordField = Pattern.compile(".*[A-Z].*[0-9]");
m = passwordField.matcher(password);
boolean legitPassword = m.matches();
*/
boolean legitPassword = true;
// This code will validate the credentials user have keyed in
// If the email code is correct
if (legitEmail) {
// If the password code is correct
if (legitPassword) {
// If the password belongs to the email
if (MemberDA.retrievePasswordBooleanByEmail(email, password) == true)
{
return 3;
}
else
{
return 0;
}
}
// If the password code is wrong
else {
return 2;
}
// If the email code is wrong
}else {
return 1;
}
}
将调用该方法并检索值...
int tempNumber = validator.loginValidator(txtLoginEmail.getText(),txtLoginPassword.getText());
if(tempNumber == 1) {
pnLogin.setBounds(511, 200, 270, 320);
System.out.println("Please enter an email.");
lblError.setText("Please enter an email.");
}
else if(tempNumber == 2) {
pnLogin.setBounds(511, 200, 270, 320);
System.out.println("The password should have at least a capital letter and a numerical digit.");
lblError.setText("<html>The password must have at least a <br />capital letter and a numerical digit.</html>");
}
else if(tempNumber == 0){
pnLogin.setBounds(511, 200, 270, 310);
System.out.println("Wrong email or password.");
lblError.setText("Wrong email or password.");
}
else if (tempNumber == 3) {
AdminAccountListAllPanel contentPane = new AdminAccountListAllPanel(myFrame);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
您是否有任何建议要改进代码?
谢谢