miercuri, 4 martie 2015

JSF Tip - Combine HTML5 client-side validation with JSF server-side validation

In this post, you can see two tips of using HTML5 client-side validation with JSF tags. Maybe, one of the most used JSF validators is the built-in required validator. Before applying other validators we need to have something to validate, so the required="true" is commonly used in <h:inputText> tags. Practically, each time the form is submitted, the required="true" is evaluated in the Process Validation phase. But, HTML5 also has a required attribute, which basically has the same role as the JSF built-in required validator, only that works on client-side, without submitting the form. So, if we use pass-through attributes, we can add the HTML5 required into equation and avoid form submission until the required inputs contains something. Of course, we keep the JSF required built-in validator also, for browsers that doesn't support HTML5 and for having server-side validation:

<!-- xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" -->
<h:form>
 Name: <h:inputText value="#{playerBean.name}" required="true" pt:required="true"/>
 <h:commandButton value="Send" action="data"/>
</h:form>


Output (left side HTML5 required effect, right-side JSF required effect):


HTML5 also provides an attribute named, formnovalidate. This is useful to skip validation and implement a Cancel like button. For example, if your form is based on  client-side validation and it doesn't contain JSF validators, you can write a Cancel button, as below:

<h:form>
 Name: <h:inputText value="#{playerBean.name}" pt:pattern=".{2,}"/>          
 E-mail: <h:inputText value="#{playerBean.email}" pt:type="email" pt:required="true"/>          
 <h:commandButton value="Send" action="data"/>
 <h:commandButton value="Cancel" action="#{playerBean.cancel()}" pt:formnovalidate="formnovalidate"/>
</h:form>

Note The Cancel button will work (the cancel() method will be invoked without client-side validation) only if you don't have JSF validators. This approach will NOT skip JSF Process Validation phase.

Niciun comentariu:

Trimiteți un comentariu