How to validate availability of username in database?

前端 未结 1 1277
暗喜
暗喜 2021-01-06 14:48

How can I validate the entered username in an input text field if it is available according to the database? I am using JSF2.

相关标签:
1条回答
  • 2021-01-06 15:51

    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" />
    
    0 讨论(0)
提交回复
热议问题