I would like to warn a user if his e-mail seems invalid, but still allow him to submit the e-mail if he wants to. As I’ve read, there’s no easy way to validate an e-mail besides sending a confirmation message, but I still wants to warn him of silly mistakes as forgetting to put “.com” after gmail.
I’m using JSF, and the code looks like the following:
XHTML
<h:inputText id="email"
required="true" requiredMessage="Required field"
value="#{signupBean.email}">
<f:ajax
event="valueChange"
listener="#{signupBean.validateEmail}"/>
</h:inputText>
<h:message for="email"/>
SignupBean
public void validateEmail(AjaxBehaviorEvent event){
if (email != null && !email.matches(emailRegex)){
String id = event.getComponent().getClientId();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Your e-mail seems invalid", "Did you miss the '@' or '.com'?");
FacesContext.getCurrentInstance().addMessage(id, msg);
}
}
As it is, the message is lost, appearing as a warning log. The id that appears is j_id_f:email, but it won’t work if I hardcode as email. Also, I’ve tried using action instead of listener, but the method isn’t even called!
I’d like some advice if that’s the way to go, or if there’s some way to do such ‘weak’ validation in JSF alone. I’m using pure JSF, but would consider using extensions.
You forgot to update the
<h:message>on complete of ajax request, so JSF simply didn’t have any chance to present the message in the UI.Fix it accordingly: