Validate two components with dynamic id - validation

Here is what I am trying to do:
I have a form with multiple pairs of input fields and a save button.
When the save button is pressed then for each pair of input fields should be validated if they are numbers and if the left value is smaller than the right value.
If not the validation errors will be shown and if it is the case a dialog will pop up to ask for the name under which it should be saved.
Here is what I got so far:
<h:form>
<ui:repeat value="#{myBean.someList}" var="elem">
<h:inputText id="min#{elem.id}" value="#{elem.minimum}" />
<h:inputText id="max#{elem.id}" value="#{elem.maximum}" />
<br />
<h:message for="min#{elem.id}" style="color:red" />
<h:message for="max#{elem.id}" style="color:red" />
</ui:repeat>
<h:commandButton value="save">
<f:ajax execute="#form" render="#form updateValidationFailedFlag"
onevent="
function(ajaxResult){
if(ajaxResult.status=='success' && !globalValidationFailedFlag)
showSaveDialog();
}"
/>
</h:commandButton>
<h:outputScript id="updateValidationFailedFlag">
globalValidationFailedFlag = #{facesContext.validationFailed};
</h:outputScript>
</h:form>
This works but doesn't check if the minimum is smaller then the maximum.
It will validate the input (checks if the input are integer) and shows the save dialog if no validation error occured.
To check if the minimum is smaller then the maximum I tried to follow the tutorial at http://www.mkyong.com/jsf2/multi-components-validator-in-jsf-2-0/
Variant 1 adds a listener after the validation is done and is able to add error messages that are shown in the browser. But that doesn't count as a validation failure and doen't set the facesContext.validationFailed flag.
Variant 2 writes a custom validator for one component and gives the other component as parameter to that validator. That would look something like this:
<f:validator validatorId="myValidator" />
<f:attribute name="maximum" value="#{max#{elem.id}}" />
That is not really valid EL and I don't know how to write it correctly.
What can I do to validate if each of those min-max pairs is valid

You don't need #{elem.id} here. The <ui:repeat> already takes care of that. It would be evaluated to an empty string anyway when JSF needs to set the id attribute.
<ui:repeat value="#{myBean.someList}" var="elem">
<h:inputText id="min" value="#{elem.minimum}" />
<h:inputText id="max" value="#{elem.maximum}" />
<br />
<h:message for="min" style="color:red" />
<h:message for="max" style="color:red" />
</ui:repeat>
As to the validation, just pass the value of the other component along:
<h:inputText id="min" binding="#{min}" value="#{elem.minimum}" />
<h:inputText id="max" value="#{elem.maximum}">
<f:validator validatorId="myValidator" />
<f:attribute name="min" value="#{min.value}" />
</h:inputText>
Note that I moved the validator to the second component. Otherwise it would be still invoked if the second component didn't pass conversion.
If you happen to use JSF utility library OmniFaces, then you could use its <o:validateOrder> instead.
<h:inputText id="min" value="#{elem.minimum}" />
<h:inputText id="max" value="#{elem.maximum}" />
<o:validateOrder components="min max" showMessageFor="min" />
See also:
How to use EL with <ui:repeat var> in id attribute of a JSF component
JSF doesn't support cross-field validation, is there a workaround?

Related

Mutually exclusive input fields with JSF and PrimeFaces

I have a PrimeFaces application where I would like to make two input text fields mutually exclusive: the user should fill either field, but not both.
In the following example, the user could search contacts either by phone number or by email.
<h:form>
<h:outputLabel>Phone Number:
<h:inputText id="phoneInput" value="#{contactSearch.phone}"
disabled="#{not empty contactSearch.email}">
<p:ajax event="keyup" update="emailInput"/>
</h:inputText>
</h:outputLabel>
<h:outputLabel>Email Address:
<h:inputText id="emailInput" value="#{contactSearch.email}"
disabled="#{not empty contactSearch.phone}">
<p:ajax event="keyup" update="phoneInput"/>
</h:inputText>
</h:outputLabel>
<!-- Possibly other fields... -->
<h:commandButton value="Search" action="#{contactSearch.search}"/>
</h:form>
Is this the proper way to do it? I am concerned about:
Possible "deadlock" issues, where both fields end up being disabled
The whole form being submitted and/or valdiated in the Ajax request, when I just would like to update the disabled state of the input field
Missing some predefined PrimeFaces control which does all the work :)
This is not trivial in standard JSF. JSF utility library OmniFaces has a validator for exactly this purpose, the <o:validateOne>.
<h:inputText id="email" ... />
<h:inputText id="phone" ... />
<o:validateOne components="email phone" />
However, in UX perspective, you'd better redesign your form to provide a single UISelectOne component to select the type and a single UIInput field to enter the value. E.g.
<h:selectOneRadio ... value="#{bean.type}">
<f:selectItem itemValue="email" />
<f:selectItem itemValue="phone" />
</h:selectOneRadio>
<h:inputText ... value="#{bean.value}" />
Update: as server side validation is not affordable and you'd really like to disable the the other without making much ajax traffic, your only bet is using pure JavaScript/jQuery for the job (if necessary in combination with server side validation as fallback).
Here's a generic jQuery based approach:
<h:inputText styleClass="onlyone" a:data-onlyone="groupName" />
<h:inputText styleClass="onlyone" a:data-onlyone="groupName" />
...
$(document).on("input", ":input.onlyone", function() {
var $this = $(this);
var $others = $("[data-onlyone='" + $this.data("onlyone") + "']").not($this);
$others.val(null).attr("disabled", !!$this.val());
});
The data-onlyone value should represent the group name, so you can have multiple of "only one" inputs throughout the document.

Performing data binding during ajax-request

I have the following markup:
<rich:panel id="selectorPanel">
<h:inputText value="#{myBean.field1}" />
<h:inputText value="#{myBean.field2}" />
<h:inputText value="#{myBean.field3}" />
<!-- and so forth -->
<h:selectOneMenu id="selector" value="#{myBean.selected}">
<a4j:ajax event="change" listener="#{myBean.doUpdateValues()}" render="selectorPanel" />
<f:selectItem itemLabel="#{msgs['bundle.addFilter']}" itemValue="#{null}" value="#{null}"/>
<f:selectItems value="#{myBean.filters}" />
</h:selectOneMenu>
</rich:panel>
The problem: when I change the value of the selectOneMenu the selectorPanel is being rerendered, therefore the values of the inputTexts are being refreshed and set to the myBean's properties value.
But I need to set values entered by user on the web-page to the corresponding bean's properties before rerendering.
Is it possible? How?
Why to do need to execute all? the #form should be enough or even list of inputs ids.
I've found the solution just now and we can actually use execute attribute as follows:
execute="#all"
It works for me.

Show previous valid value of h:selectOneListbox when invalid selection is made

I have a problem with the validation of a selectOneListBox. Everything works fine and a message is displayed, when the input is false. But the dropdown keeps the selected value as the dropdown value. I want to display the old value if validation fails.
So how can I do that?
I tried this:
<h:selectOneListbox id="intFrom" value="#{searchBean.intFrom}" size="1" immediate="true" class="intSelectBox1">
<f:ajax render=":menuForm :searchForm:searchButton" listener="#{menuBean.focus(menuBean.mySearch)}" />
<f:ajax listener="#{searchBean.count()}" render="int1" />
<f:ajax execute="intFrom" render="intFrom" />
<f:selectItems value="#{searchBean.intRangeFrom}" />
<f:validator validatorId="project.IntFromValidator" />
</h:selectOneListbox>
<h:message id="int1" for="intFrom" style="color: red" />
But after that the new value is being displayed not the old one.

h:inputText is not ajax-rendered on change of h:selectOneMenu

I have this code which is used to select how many rows to display in jsf table:
<!-- Set rows per page -->
<h:outputLabel for="rowsPerPage" value="Rows per page" />
<h:inputText id="rowsPerPage" value="#{AccountsController.rowsPerPage}" size="3" maxlength="3" />
<h:commandButton styleClass="bimage" value="Set" action="#{AccountsController.pageFirst}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:message for="rowsPerPage" errorStyle="color: red;" />
I want to edit the code this way: I want to replace the code with h:selectOneManu and option to insert custom value with AJAX support:
<h:selectOneMenu id="setrows" value="#{AccountsController.rowsPerPage}" converter="javax.faces.Integer" maxlength="3">
<f:selectItem itemValue="10" itemLabel="10" />
<f:selectItem itemValue="50" itemLabel="50" />
<f:selectItem itemValue="100" itemLabel="100" />
<f:selectItem itemValue="500" itemLabel="500" />
<f:selectItem itemValue="332" itemLabel="Custom" />
<f:ajax render="customrowperpage" />
</h:selectOneMenu>
<h:inputText id="customrowperpage" value="#{AccountsController.rowsPerPage}" rendered="#{AccountsController.rowsPerPage == '332'}" required="true" />
But for some reason the code is not working. Can you help me to find the problem. Also I want to update AJAX functionality when I select number from the h:selectOneMenu list AJAX call to update the form.
There are 2 problems.
First, as JavaScript runs in the client side, you can't ajax-update a JSF component which isn't rendered to the client side. There's then simply nothing in the HTML DOM tree which JavaScript can select, manipulate and replace. You should instead ajax-update a JSF component which is always rendered to the client side.
<h:panelGroup id="customrowperpage">
<h:inputText value="#{AccountsController.rowsPerPage}" required="true"
rendered="#{AccountsController.rowsPerPage == '332'}" />
</h:panelGroup>
See also Why do I need to nest a component with rendered="#{some}" in another component when I want to ajax-update it?
Second, an Integer never equals a String. You're in the rendered attribute testing Integer rowsPerPage against String '332'. Remove those singlequotes to make it a fullworthy number.
<h:panelGroup id="customrowperpage">
<h:inputText value="#{AccountsController.rowsPerPage}" required="true"
rendered="#{AccountsController.rowsPerPage == 332}" />
</h:panelGroup>

Temporarily disable JSF validations

A has many required inputs and validations. A couple of command buttons control different inputs.
I can change required attibrute with the value of <f:param>. For instance when a button is clicked,it sets a value.This value changes if an input is required or not. Like this:
<p:commandButton>
<f:param name="button1" value="1"></f:param>
</p:commandButton>
<h:inputText required="#{param['button1'] == 1}"></h:inputText>
This actually works.However i also want to add some valitations like max length.I want to temporarily change this validation too.
I tried to disable valitadion,but i did not work:
<f:validateLength disabled="true" maximum="10"></f:validateLength>
You seem to be using JSF 2.x already. So just use <f:ajax execute> or <p:commandButton process> to specify client IDs of components which are to be executed/processed when the button is pressed. All components which are not included in this will just be ignored and not converted/validated.
E.g.
<h:inputText id="input1" ... required="true" />
<h:inputText id="input2" ... required="true" />
<h:inputText id="input3" ... required="true" />
<h:inputText id="input4" ... required="true" />
<p:commandButton value="Submit inputs 1 and 2" process="input1 input2" ... />
<p:commandButton value="Submit inputs 3 and 4" process="input3 input4" ... />
In case of <p:commandButton> it defaults to #form (i.e. the entire current form).
See also:
Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Resources