バッキング Bean アクション メソッドではなく、通常のValidator
.
例えば
<h:inputText value="#{register.email}" required="true" validator="#{emailValidator}" />
<h:inputSecret binding="#{password}" value="#{register.password}" required="true" />
<h:inputSecret required="true" validator="confirmPasswordValidator">
<f:attribute name="password" value="#{password.value}" />
</h:inputSecret>
...
このような#{emailValidator}
もので:
@MangedBean
public class EmailValidator implements Validator {
@EJB
private UserService userService;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null) {
return; // Let required="true" handle.
}
if (userService.existsEmail((String) value)) {
throw new ValidatorException(Messages.createError("Email already exists"));
}
}
}
EJB はここで例外をスローしないことに注意してください。これは、DB のダウンや間違ったテーブル/列の定義など、致命的で回復不能なエラーが発生した場合にのみ行う必要があります。
そして、confirmPasswordValidator
このようなものです
@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object password = component.getAttributes().get("password");
if (value == null || password == null) {
return; // Let required="true" handle.
}
if (!password.equals(value)) {
throw new ValidatorException(Messages.createError("Password do not match"));
}
}
}