All blog posts, code samples and downloads licensed under Apache License 2.0.
Close

Dependent field validation

Oliver Busse on 02/27/2013 18:11:39 CET, filed under SSJS XSP 

If you want to validate a field depending on a value of another field than you may find this helpful.

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

	<xp:inputText id="inputText1" disableClientSideValidation="true"
		required="true">
		<xp:this.validators>
			<xp:validateRequired message="Field 1 is required"></xp:validateRequired>
			<xp:customValidator>

				<xp:this.validate><![CDATA[#{javascript:var field1 = getComponent('inputText1')
var field2 = getComponent('inputText2')

var fieldVal1 = field1.getSubmittedValue()
var fieldVal2 = field2.getSubmittedValue()

if(fieldVal1.equals('abc') && fieldVal2.equals('')){
	var msg = 'field 2 is required when field 1 is "abc"'
	var msgObj = new javax.faces.application.FacesMessage( 
              javax.faces.application.FacesMessage.SEVERITY_ERROR, msg, msg 
      ); 
	facesContext.addMessage(field2.getClientId(facesContext), msgObj)
	field2.setValid(false)
}
}]]></xp:this.validate>
			</xp:customValidator>
		</xp:this.validators>
	</xp:inputText>

	<xp:br></xp:br>
	<xp:inputText id="inputText2" disableClientSideValidation="true">
	</xp:inputText>
	<xp:br></xp:br>
	<xp:br id="br1"></xp:br>
	<xp:messages id="messages1"></xp:messages>
	<xp:br></xp:br>
	<xp:br></xp:br>
	<xp:button value="Label" id="button1">
		<xp:eventHandler event="onclick" submit="true"
			refreshMode="complete">
		</xp:eventHandler>
	</xp:button>
</xp:view>

As the custom validator is executed only if a value is submitted you cannot calculate the required validator for the second field. Therefor you have to put the custom validator in the first field. This sample assumes that the first field is required.

Notice: the custom validator is only executed if the required validator comes in action.

Just create a blank XPage and paste the code below into it to see how it works. Test it with some values for the first field and then try the value "abc" and see what happens.

Many thanks to Sven Hasselbach who gave me the hint Lächelnd


Tagged with validation