私はこの検証機能を持っています。データベースに対してログインフォームを検証します。Javaは式username.isEmpty()
をpassword.isEmpty()
2回テストしますか? 前者は
if ((!username.isEmpty()) && (!password.isEmpty()))
、後者は
if(username.isEmpty())
error.addError("username", "Username is mandatory.");
if(password.isEmpty())
error.addError("password", "Password is mandatory.");
?
同じテストをやり直さないように、最初のテストの結果を「保存」する内部メカニズムはありますか? パフォーマンスを維持したいと同時に、エラー Bean を埋めなければなりません。正規表現 (例: 登録フォーム) で複雑な、より多くのチェックを含むより多くのフィールドを配置したい場合はどうなりますか? その機能はまだ良いでしょうか?私が従いたい基本原則は次のとおりです。すべてのテストに合格した場合にのみ、フラグに true を割り当てます (またはコードを入力します)。それ以外の場合は false になります (デフォルト)。その逆ではありません (フラグはデフォルトで true ですが、false になる可能性があります)。
私の英語が悪く聞こえたら、遠慮なく訂正してください。ありがとう。
public boolean validate(FormBean bean, FormErrorBean error)
{
// the validation flag
boolean valid = false;
if (bean instanceof LoginFormBean)
{
// check not null
if (!bean.isEmpty())
{
String username = ((LoginFormBean) bean).getUsername();
String password = ((LoginFormBean) bean).getPassword();
if ((!username.isEmpty()) && (!password.isEmpty()))
{
// create the DAO
UserDao uDao = new UserDao();
// check the user
valid = uDao.checkUser((LoginFormBean) bean);
// set the validation status of the bean
((LoginFormBean) bean).setValid(valid);
// add the error, if any
if (!valid)
error.addError("Either the username is not valid or the password is wrong.");
}
else
{
if(username.isEmpty())
error.addError("username", "Username is mandatory.");
if(password.isEmpty())
error.addError("password", "Password is mandatory.");
}
}
else
{
// add the empty error...
error.addError("Both the username and password are missing.");
}
}
return valid;
}