Sunday, May 19, 2013

How to use jQuery validation plugin in JSF

jQuery validation plugin is a lightweight, easy to use and powerful validation tool.
But when we want to use it with JSF, some special handling are required for it to work, due to the JSF component's clientId.

In this article, Primefaces 3.5 is used, and solution demonstrated below should be suitable for all other JSF implementations.

Steps:
1. Create the form and components that required validation.
<h:form id="myform">
  <p:inputText id="emailAddr" value="#{user.email}" />
</h:form>

2. If the target project is not JSF (strust, servlet, etc), the following syntax used.
<script>
$(document).ready(function(){
$("#myform").validate({
    rules: {
        emailAddr: {
            email: true
            }
        }
    });
});
</script>

because the component's clientId is generated by JSF, normally the clientId is in the following format - 'formId' + ':' + 'componentId'.
in this case, the clientId is going to be myform:emailAddr
By changing the clientId only is not enough, because the semicolon(:) in between the clientId may confuse jQuery.
Thus, we need to append single quote (') in front and behind of the clientId.
in this case, the clientId is going to be 'myform:emailAddr'


Solution:

<script>
$(document).ready(function(){
$("#myform").validate({
    rules: {
        'myform:emailAddr': {
            email: true
            }
        }
    });
});
</script>

Complete source for jQuery validation plugin in JSF:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js" />
 <script>
 $(document).ready(function(){
     $("#myform").validate({
         rules: {
      'myform:emailAddr': {
          email: true
          }
      }
  });
     });
 </script>
    </h:head>
<h:body> 
    <h:form id="myform">
        <p:inputText id="emailAddr" value="#{user.email}" />
    </h:form> 
</h:body>
</html>


Done!!


LinkWithin

Related Posts Plugin for WordPress, Blogger...