[SalesForce] Required field validation error message in VF Page using Javascript? (No Alert box or Popup’s)

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

Best Answer

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">
    <apex:form>
            <!-- 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"/>
    </apex:form>
</apex:page>

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