Email validation with JSF and Java Studio Creator

This is a really an old post (2005). If you’re looking for something more modern, checkout this validation sample based on (Java EE 6) Bean Validation (JSR 303).

Reading this tip and not finding anything on the web (not even on Tor’s excellent blog). Here’s a quick example of a standard HtmlInputText component and its regexp email validator.


Using Creator, simply drop a label, a textfield, and a button on the page canvas. Add also an inline message (HtmlMessage) and link it using Ctrl-Shift drag and drop to the textfield.

Right-click on the text field and choose “validate”.
Here’s an example of code you could use to fill in the generated emailField_validate() method body (I renamed the component to emailField in the Properties window) :

    public void emailField_validate(FacesContext fc,
                  UIComponent uic, Object o) {
       String email = (String) o;

       if (!email.matches(".+@.+\\\\.[a-z]+")) {
          ((UIInput)uic).setValid(false);
          throw new ValidatorException(
                  new FacesMessage("Invalid Email"));
       }

    }

(make sure you auto-import ValidatorException and FacesMessage using Shift-Alt-I).


The use of setValid(false) is optional. Even if the “Submit” button is not linked to anything (not action event handler), the JSF request lifecycle will trigger the validator we just set up and the page and its view tree will be regenerated. Throwing an exception will trigger the error message (hard-coded in this example) to be displayed in the inline message component.

Now of course, you could also be using a custom JSF component.

Author: alexismp

Google Developer Relations in Paris.