如何验证数据库中用户名的可用性? [英] How to validate availability of username in database?

查看:72
本文介绍了如何验证数据库中用户名的可用性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果根据数据库可用,如何验证输入文本中的用户名?我正在使用JSF2.

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"));
        }
    }

}

(请注意,它是一个@ManagedBean而不是@FacesValidator,因为需要注入一个@EJB;如果您不使用EJB,则可以将其设置为@FacesValidator)

(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)

按以下方式使用它:

<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" />

这篇关于如何验证数据库中用户名的可用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆