XPages: Validating Radio Groups Client Side
Steve Castledine 17 February 2010 09:45:48
This has come up twice recently so thought I would share a few tips.Server side validation of radio groups and also check box groups on a basic level is very simple. You navigate to the component properties and add a "required" (xp:validateRequired) validation rule via data > validators.
I say simple however other components do have this available on a specific validation tab whereas these you have to drill down to the properties:
If you want to do more advanced validation then the value is available via getComponent("radiogroup").getValue(). Depending on where on the page you are trying to validate the value (maybe before the component) you may need to use getSubmittedValue() instead but mostly getValue() is what you would use.
Client side is a little trickier, as just like any web application and javascript accessing of radio group values its not available as a single value but as independent values of the radio group (or check box) child values.
To make it harder you have to get values via the "form" element and even harder I find JSF style name's are not liked in browsers for looking up named elements of a form (at least it was a struggle for me) so you have to traverse the entire form to get the element you need and then get the value you want.
The code below is an example of what I mean. First it goes through all the form elements to find what we need, then it iterates through the child elements to find the value. Note how it uses #{id:myRadioGroupID} to calculate the eventual component name (which may actually be: view:_id1:myRadioGroupID).
var result=null;
for(var i=0; i<document.forms[0].elements.length; i++){
if(document.forms[0].elements[i].name=="#{id:myRadioGroupID}" ){
if(document.forms[0].elements[i].checked == true){
result=document.forms[0].elements[i].value;
break; //remove this if for check box groups and collect multiple values above instead
}}}
alert(result);
for(var i=0; i<document.forms[0].elements.length; i++){
if(document.forms[0].elements[i].name=="#{id:myRadioGroupID}" ){
if(document.forms[0].elements[i].checked == true){
result=document.forms[0].elements[i].value;
break; //remove this if for check box groups and collect multiple values above instead
}}}
alert(result);
- Comments [1]
