[SalesForce] how to make field required via javascript

Depending on the value of a picklist I'd like to toggle a set of fields from required to not required. I've been able to add the divs to make it look required 'red bar in inputField'. Its still not actually being required though. Before I write my own validation I wanted to see if there's an easier way to do this that I'm not thinking of.

Here's what I have right now:

function setRequiredPaymentFields() {
        var paymentMethod= $j("[id$='paymentMethod']").val();

        if (paymentMethod=='Credit Card') {
            $j('.invoice').hide();
            $j('.creditCard').show().wrap('<div class="requiredInput"/>').before('<div class="requiredBlock"></div>');

        }
    }

Any suggestions?

Best Answer

You can use a combination of the required attribute and <apex:actionFunction> to enforce conditional required behaviour.

Here is an example with Account as StandardController, where the Account Phone becomes mandatory, if the Account Type is 'Other', reverts back to not mandatory otherwise.

 <apex:page StandardController="Account">

    <script>
function setRequired(){
    if(document.getElementById('{!$Component.theForm.thePageBlock.thePageBlockSection.accPhone}').value == '') 
    document.getElementById('{!$Component.theForm.thePageBlock.thePageBlockSection.accPhone}').value = '0';

    reRenderBlock();
    }
    </script>

      <apex:form id="theForm">

      <apex:actionFunction name="reRenderBlock" rerender="thePageBlock"/>

      <apex:pageBlock id="thePageBlock">
      <apex:pageBlockSection id="thePageBlockSection">
      <apex:inputField id="accPhone" value="{!Account.Phone}" required="{!Account.Type == 'Other'}"/>
      <apex:inputField value="{!Account.Type}" onchange="setRequired();"/>

      </apex:pageBlockSection>

      </apex:pageBlock>
      </apex:form>
    </apex:page>

(The only slight quirk I've had to use is set the field value to '0' when it is blank, and when the field needs to change back to non-required, because it would give you an error for a missing value or else)