How can I validate the entered username in an input text field if it is available according to the database? I am using JSF2.
如果根据数据库可用,在输入文本字段中如何验证输入的用户名?我正在使用JSF2。
1 个解决方案
#1
5
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)
(请注意,它是@ManagedBean而不是@FacesValidator,因为需要注入@EJB;如果你不使用EJB,你可以改为使用@FacesValidator)
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" />
#1
5
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)
(请注意,它是@ManagedBean而不是@FacesValidator,因为需要注入@EJB;如果你不使用EJB,你可以改为使用@FacesValidator)
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" />