How to validate availability of username in database?

前端 未结 1 1291
暗喜
暗喜 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:

    
        
        
    
    
    

    0 讨论(0)
提交回复
热议问题