0

I am currently trying to validate user input on a JSF xhtml page. I would like to print out the error message and keep the program going for next input/transaction after the exception is caught. Is it possible?

Log or throw more exception only brings me to a broken page but I would like to have the user to have a chance to reenter.

if(!input.equals("")){
    try{
        String sanitized = Sanitizer.sanitizeInput(input);
        if(sanitized.equals("")){
            throw new UnsafeInputException("Please try again.");
        }
    } catch(UnsafeInputException err){
        // what should I do here?
    }
}
Kukeltje
  • 12,223
  • 4
  • 24
  • 47
Samuel Fu
  • 1
  • 1
  • What not start with some good jsf tutorials? These basic things are all in there. https://jsf.zeef.com/bauke.scholtz – Kukeltje Oct 15 '19 at 19:25

1 Answers1

0

Add to your xhtml page the following tag:

<h:messages />

It will display your messages at this position and can be styled.

To display messages from your managed bean, use the following code. It will add your message at the position where the <h:messages/> is located

String sanitized = Sanitizer.sanitizeInput(input);
if(sanitized.equals("")){
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your error message"); 
} 
alea
  • 980
  • 1
  • 13
  • 18
  • Thank you so much that makes so so much sense! One more question: can I add multiple messages to current instance? how did the h:message tag know which one to read from? By doing so does it stop the current program and make it ready for next operation? Maybe dumb don’t mind thank you in advance! – Samuel Fu Oct 16 '19 at 19:42