I’m running a JSF 2.0 application on Tomcat 7. I want to use javascript for form validation. Here is a simplified version of my problem:
I have two jsf files index.xhtml and result.xhtml and one file with javascript code. Both xhtml files are in apps root folder.
In index.xhtml:
<h:head>
<h:outputScript name="script.js" library="js" />
</h:head>
<h:body>
<h:form>
<h:inputSecret id="password" />
<h:inputSecret id="confirm" />
<h:commandButton
type="button"
value="go"
action="result"
onclick="checkPassword(this.form)" />
</h:form>
</h:body>
script.js:
function checkPassword(form){
var password = form[form.id+":password"].value;
var confirm = form[form.id+":confirm"].value;
alert(password + " " + confirm);
if(password == confirm){
form.submit();
}else{
alert("Password doesn't match");
}
}
The content of result.xhtml is insignificant. When I run this index.xhtml I get what I expected. When I fill the textboxes with the same values and click the button the checkPassword function is triggered but the browser stays on index.xhtml and I want it to forward to result.xhtml. What am I doing wrong? I’m interested not only in a walkaround but in a reason why it’s not working. Can you help me?
The navigation is performed by executing the command button’s action, not by submitting alone the form. You’re basically suppressing the default action of the button by calling
form.submit(). This way JSF won’t be able to find out which command button was pressed during submitting the form. You should instead be returningtrueorfalsedepending on the validation result. If you returntrue, then the button’s default action will be continued as usual.Change your onclick handler to
and your JS code to
Unrelated to the concrete problem, this isn’t the best way of validating input. As JavaScript runs fully at the client side, the enduser has full control over its process. The enduser can disable JavaScript altogether or even manipulate/bypass the code.
Rather do the validation fully in server side using a normal JSF
Validator. You can use<f:ajax>to have instant validation and thus improve user experience. Showing JS alerts is also soo 90’s. Rather use JSF’s own<h:message>facility to display the message in the page itself.