[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??
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.
There are some issues with your validation construct.
First the action attribute of the apex:actionSupport is not for the javascrict functions but for controller methods. Then don't forget to use braces if calling an apex method from the visualforce page action = "{!SSave}".
Use merge-field syntax to reference the method. For example,
action="{!incrementCounter}" references the incrementCounter() method
in the controller. If an action is not specified, the page simply
refreshes.
Then i would do a validation after user submits the form (click on "Submit" button). We will invoke a validation javascript function and need to insert a return false; otherwise the page will be reloaded. In this examle i will not use a commandLink because i will not call any apex method from it. This work will take an actionFunction after validation is finished.
<apex:actionFunction name="saveNow" action="{!SSave}"/>
<apex:inputField value="{!selectValue}" id="myField"/>
<input type="button" value="Submit" class="btn" onclick="doValidation();">
<script>
function doValidation(){
if(document.getElementById('{!$Component.myField}').value != ''){
saveNow();
}
else{
alert('Please fill out all fields!');
}
}
</script>
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:
Js Code in form validate function: