How to write Javascript validation for Visualforce page?
Sample Code:
Visualforce Page:
<apex:page controller="Sample" >
<!-- Javascript -->
<script type="text/javascript">
function validate()
{
if(document.getElementById('{!$Component.frm.pb.pbs.pbsi1.nam}').value == '')
{
alert("Account name is mandatory");
}
if(document.getElementById('{!$Component.frm.pb.pbs.pbsi2.extid}').value == '')
{
alert("External id is mandatory");
}
else
{
callSubmt();
alert("Account has been inserted");
}
}
</script>
<!-- Javascript -->
<apex:form id="frm">
<apex:actionFunction action="{!submt}" name="callSubmt" reRender="pb"/>
<apex:pageBlock id="pb">
<apex:pageBlockSection id="pbs">
<apex:pageBlockSectionItem ><apex:outputLabel value="Account Name"/></apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="pbsi1"><apex:inputText value="{!nam}" id="nam"/></apex:pageBlockSectionItem>
<apex:pageBlockSectionItem ><apex:outputLabel value="External Id"/></apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="pbsi2"><apex:inputText value="{!extId}" id="extid"/></apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton value="Insert" onclick="validate();"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex Controller:
public class Sample
{
public Account acc = new Account();
public String extId{get;set;}
public String nam{get;set;}
public void submt()
{
acc.Name = nam;
acc.Ext_Id__c = extId;
insert acc;
}
}
Output:
Visualforce Page:
<apex:page controller="Sample" >
<!-- Javascript -->
<script type="text/javascript">
function validate()
{
if(document.getElementById('{!$Component.frm.pb.pbs.pbsi1.nam}').value == '')
{
alert("Account name is mandatory");
}
if(document.getElementById('{!$Component.frm.pb.pbs.pbsi2.extid}').value == '')
{
alert("External id is mandatory");
}
else
{
callSubmt();
alert("Account has been inserted");
}
}
</script>
<!-- Javascript -->
<apex:form id="frm">
<apex:actionFunction action="{!submt}" name="callSubmt" reRender="pb"/>
<apex:pageBlock id="pb">
<apex:pageBlockSection id="pbs">
<apex:pageBlockSectionItem ><apex:outputLabel value="Account Name"/></apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="pbsi1"><apex:inputText value="{!nam}" id="nam"/></apex:pageBlockSectionItem>
<apex:pageBlockSectionItem ><apex:outputLabel value="External Id"/></apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="pbsi2"><apex:inputText value="{!extId}" id="extid"/></apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton value="Insert" onclick="validate();"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex Controller:
public class Sample
{
public Account acc = new Account();
public String extId{get;set;}
public String nam{get;set;}
public void submt()
{
acc.Name = nam;
acc.Ext_Id__c = extId;
insert acc;
}
}
Output:
No comments:
Post a Comment