views:

296

answers:

4

I have a situation in my form that the user must fill at least one of the fields. Using "required" command, i cannot do that. What is the best way to validate this in seam ? i dont want to use javascript.

Thanks!

A: 

JSF2 will let you do a form-level validation. For now, you'll have to make do with either:

  • Validate in a Bean after form submission and populate a FacesMessage to the user if it fails.
  • Add a validator to one field and in that validator load in the other fields and check their values.
Damo
+1  A: 

Just let the required attribute depend its outcome on the presence of the other input fields in the request parameter map.

<h:form id="form">
    <h:inputText id="input1" value="#{bean.input1}" required="#{empty param['form:input2'] and empty param['form:input3']}" />
    <h:inputText id="input2" value="#{bean.input2}" required="#{empty param['form:input1'] and empty param['form:input3']}" />
    <h:inputText id="input3" value="#{bean.input3}" required="#{empty param['form:input1'] and empty param['form:input2']}" />
</h:form>

Alternatively you could also make use of component binding and use UIInput#getValue() to check the value of the previous components and UIInput#getSubmittedValue() to check them for the yet-to-be-validated components (components are processed in the order as they appear in the component tree). This way you don't need to hardcode client ID's. You only need to ensure that binding names doesn't conflict with existing managed bean names.

<h:form>
    <h:inputText binding="#{input1}" required="#{empty input2.submittedValue and empty input3.submittedValue}" />
    <h:inputText binding="#{input2}" required="#{empty input1.value and empty input3.submittedValue}" />
    <h:inputText binding="#{input3}" required="#{empty input1.value and empty input2.value}" />
</h:form>
BalusC
A: 

If you dont want to use required attribute or javascript, then there are two ways.

One of them is creating a validator, but in my opinion that is too overkill.

I would just check if the input is null or empty in your bean.

if ("".equals(theFieldYouWantToCheck) || theFieldYouWantToCheck == null) {
 //Either throw exception or return "false" so that you can handle it
}
Shervin
A: 

If you are using RichFaces then you could perform the validation as follows (see http://mkblog.exadel.com/ria/richfaces-ria/richfaces-built-in-client-functions/):

<h:form id="form">
    <h:inputText id="input1" value="#{bean.input1}" />
    <h:inputText id="input2" value="#{bean.input2}" 
        required="#{empty rich:findComponent('input1').submittedValue}"  
        requiredMessage="At least one of the fields input1 and input2 must be filled."/>
</h:form>

Note that the expression rich:findComponent('input1') is equivalent to uiComponent['input1']. The reason is that Seam provides the dynamic map uiComponent to look up UI components.

vsommerfeld