I want simple message 'Complete this field' (as shown in image below) to displayed under input boxes which are empty while submitting the form in VisualForce page.

Can someone tell me how to accomplish this using JavaScript code??

enter image description here


You can create span below the input box, initially it will not be visible, but whenever form is submitted, you can check for values and make it visible if there is no value for the input.

This is pseudo code:

VF Code:

<apex:page id="page" controller="Controller">
            <!-- some code here -->
            <apex:inputField id="inputfieldId1" value="{!object.field}" />
            <div id="errorInputfieldId1" style="color:red;display:none;">Complete this field!</div>
            <!-- some code here -->
            <apex:commandButton onclick="return validateform();" action="{!yourAction}" value="Save"/>

Js Code in form validate function:

function validateform(){
    var field = document.querySelector('[id$="inputfieldId"]');
    var error = document.getElementById("errorInputfieldId1");
    if(x.value == null ){
        error.style.display = 'block';
    } else {
        error.style.display = 'none';

    //same you can repeat for other fields.
    //if all fields valid, then return true; else false.

Note : You can also achieve this using required="true" attribute of apex:inputField. You just need to put attribute, everything else is handled by Salesforce.

Eg: <apex:inputField value="{!object.field}" required="true"/>


Well the first thing that comes into my mind is to use:

 <aura:if isTrue="{!v.Error}">
                    <div> Error message </div>

You can place this under each input field you have, make it nice with CSS and simply change value of v.Error variable to true when you need to show the error.

Initially Error whould be declared as follows:

<aura:attribute name="Error" type="boolean" default="false"/>

Then from JS you can simply access it using:

cmp.set('v.Error', true)

I hope it helps

  • 1
    I am working in VisualForce Page – user62549 Jan 8 '19 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy