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??
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 ofapex: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>
</aura:if>
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.get('v.Error')
cmp.set('v.Error', true)
I hope it helps