Find your content:

Search form

You are here

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('.creditCard').show().wrap('<div class="requiredInput"/>').before('<div class="requiredBlock"></div>');


Any suggestions?

Attribution to: Phil B

Possible Suggestion/Solution #1

I would suggest using Salesforce's validation rules. These server-side rules can be very complex if needed and are easier to maintain than JavaScript though they cannot dynamically alter a page's appearance.


Response to question in comments: Validation rules cannot be set specifically by pages, but one workaround is to use Record Types. Using Opportunities as an example, if the Record Type Normal used the standard pages but Special needed the validation you would just add that as a check in the validation rule. If there are no differences to distinguish the records that might make a validation rule impossible.

I highly recommend that validation rules be consistent regardless of the UI, otherwise you risk having inconsistent/bad data.

Attribution to: Mike Chale

Possible Suggestion/Solution #2

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">

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


      <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();"/>



(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)

Attribution to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content