How can I validate the entered username in an input text field if it is available according to the database? I am using JSF2.
Just implement a Validator yourself.
@ManagedBean
@RequestScoped
public class UserNameAvailableValidator implements Validator {
@EJB
private UserService userService;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String userName = (String) value;
if (!userService.isUsernameAvailable(userName)) {
throw new ValidatorException(new FacesMessage("Username not avaliable"));
}
}
}
(please note that it's a @ManagedBean
instead of @FacesValidator
because of the need to inject an @EJB
; if you're not using EJBs, you can make it a @FacesValidator
instead)
Use it as follows:
<h:inputText id="username" value="#{register.user.name}" required="true">
<f:validator binding="#{userNameAvailableValidator}" />
<f:ajax event="blur" render="username_message" />
</h:inputText>
<h:message id="username_message" for="username" />