public class Register {
@NotNull private String password;
@NotNull private String passwordRepeat;
@AssertTrue private boolean comparePasswords() {
return password.equals(passwordRepeat);
}
private Set<ConstraintViolation<Register>> violations;
public void doRegister(AjaxBehaviorEvent event) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
violations = validator.validate(this);
if(violations.isEmpty()) {
// This occurs
}
}
}
両方のパスワードが null ではなく、異なる場合、検証はパスします。理由はわかりませんが、最後の制約は考慮されないようです。誰か提案がありますか?
いいえ、@Matches や類似のカスタム バリデータの実装を探しているわけではありません。この問題を解決したいだけです。
前もって感謝します。
更新 1
これに関していくつかのテストを実行しましたが、結果が必要な情報を提供することを願っています。
Bean.java
@Named
@RequestScoped
public class Bean {
@NotNull private String example1;
@NotNull private String example2;
@AssertTrue private boolean examplesMatch() { return example1.equals(example2); }
private Set<ConstraintViolation<Bean>> violations;
private FacesContext context;
private Validator validator;
@PostConstruct
public void init() {
context = FacesContext.getCurrentInstance();
validator = Validation.buildDefaultValidatorFactory().getValidator();
example1 = "abc";
example2 = "def";
runValidation(false, 1);
example1 = "abc";
example2 = "abc";
runValidation(true, 2);
example1 = "abc";
example2 = null;
runValidation(false, 3);
}
private void runValidation(boolean assertion, int testNr) {
FacesMessage message;
violations = validator.validate(this);
if(violations.isEmpty() == assertion) {
message = new FacesMessage("Passed test nr. " + testNr);
}
else {
message = new FacesMessage("Failed test nr. " + testNr);
}
context.addMessage(FacesMessage.FACES_MESSAGES, message);
}
index.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>TODO supply a title</title>
</head>
<body>
#{bean}
<h:messages />
</body>
</html>
結果
beanvalidation.Bean@31c5c3da
Failed test nr. 1
Passed test nr. 2
Passed test nr. 3